利用java socket实现文件传输 java socket传送文件

\u600e\u4e48\u7528Java\u5b9e\u73b0\u4f7f\u7528TCP\u534f\u8bae\u5b9e\u73b0\u6587\u4ef6\u4f20\u8f93\u7a0b\u5e8f

\u670d\u52a1\u7aef\u76d1\u542c\uff1aServerSocket server=new ServerSocket(port);//port\uff1a\u7ed1\u5b9a\u7684\u7aef\u53e3\u53f7
Socket client=server.accept();//\u76d1\u542c\u7aef\u53e3\uff0c\u4e00\u65e6\u53d6\u5f97\u8fde\u63a5\u5219\u83b7\u5f97\u5ba2\u6237\u7aef\u7684socket\u8fde\u63a5\u5bf9\u8c61client

\u5ba2\u6237\u7aef\uff1a Socket s=new Socket(ip,port);//\u8981\u8fde\u63a5\u7684\u670d\u52a1\u5668\u7684ip\u4ee5\u53ca\u7aef\u53e3\u53f7

\u5982\u679c\u6b63\u5e38\u8fde\u63a5\u4e0a\u4e4b\u540e\uff0csocket\u7684\u5bf9\u8c61\u53ef\u4ee5\u83b7\u5f97InputStream\u548cOutputStreame\uff0c\u7136\u540e\u5c31\u53ef\u4ee5\u8fdb\u884c\u901a\u4fe1\u4e86

\u5b8c\u6210\u901a\u4fe1\u4e4b\u540e\uff0c\u6267\u884csocket\u5bf9\u8c61\u7684close\uff08\uff09\u65b9\u6cd5\u5173\u95ed\u8fde\u63a5\uff0c\u5b8c\u6210\u4e00\u6b21\u5b8c\u6574\u7684socket\u8fde\u63a5

\u5ba2\u6237\u7aef\u4ee3\u7801\u5982\u4e0b\uff1a
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; /** * \u6587\u4ef6\u53d1\u9001\u5ba2\u6237\u7aef\u4e3b\u7a0b\u5e8f * @author admin_Hzw * */ public class BxClient { /** * \u7a0b\u5e8fmain\u65b9\u6cd5 * @param args * @throws IOException */ public static void main(String[] args) throws IOException { int length = 0; double sumL = 0 ; byte[] sendBytes = null; Socket socket = null; DataOutputStream dos = null; FileInputStream fis = null; boolean bool = false; try { File file = new File("D:/\u5929\u554a.zip"); //\u8981\u4f20\u8f93\u7684\u6587\u4ef6\u8def\u5f84 long l = file.length(); socket = new Socket(); socket.connect(new InetSocketAddress("127.0.0.1", 48123)); dos = new DataOutputStream(socket.getOutputStream()); fis = new FileInputStream(file); sendBytes = new byte[1024]; while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) { sumL += length; System.out.println("\u5df2\u4f20\u8f93\uff1a"+((sumL/l)*100)+"%"); dos.write(sendBytes, 0, length); dos.flush(); } //\u867d\u7136\u6570\u636e\u7c7b\u578b\u4e0d\u540c\uff0c\u4f46JAVA\u4f1a\u81ea\u52a8\u8f6c\u6362\u6210\u76f8\u540c\u6570\u636e\u7c7b\u578b\u540e\u5728\u505a\u6bd4\u8f83 if(sumL==l){ bool = true; } }catch (Exception e) { System.out.println("\u5ba2\u6237\u7aef\u6587\u4ef6\u4f20\u8f93\u5f02\u5e38"); bool = false; e.printStackTrace(); } finally{ if (dos != null) dos.close(); if (fis != null) fis.close(); if (socket != null) socket.close(); } System.out.println(bool?"\u6210\u529f":"\u5931\u8d25"); } }\u670d\u52a1\u7aef\u4ee3\u7801\u5982\u4e0b\uff1a
import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Random; import com.boxun.util.GetDate; /** * \u63a5\u6536\u6587\u4ef6\u670d\u52a1 * @author admin_Hzw * */ public class BxServerSocket { /** * \u5de5\u7a0bmain\u65b9\u6cd5 * @param args */ public static void main(String[] args) { try { final ServerSocket server = new ServerSocket(48123); Thread th = new Thread(new Runnable() { public void run() { while (true) { try { System.out.println("\u5f00\u59cb\u76d1\u542c..."); /* * \u5982\u679c\u6ca1\u6709\u8bbf\u95ee\u5b83\u4f1a\u81ea\u52a8\u7b49\u5f85 */ Socket socket = server.accept(); System.out.println("\u6709\u94fe\u63a5"); receiveFile(socket); } catch (Exception e) { System.out.println("\u670d\u52a1\u5668\u5f02\u5e38"); e.printStackTrace(); } } } }); th.run(); //\u542f\u52a8\u7ebf\u7a0b\u8fd0\u884c } catch (Exception e) { e.printStackTrace(); } } public void run() { } /** * \u63a5\u6536\u6587\u4ef6\u65b9\u6cd5 * @param socket * @throws IOException */ public static void receiveFile(Socket socket) throws IOException { byte[] inputByte = null; int length = 0; DataInputStream dis = null; FileOutputStream fos = null; String filePath = "D:/temp/"+GetDate.getDate()+"SJ"+new Random().nextInt(10000)+".zip"; try { try { dis = new DataInputStream(socket.getInputStream()); File f = new File("D:/temp"); if(!f.exists()){ f.mkdir(); } /* * \u6587\u4ef6\u5b58\u50a8\u4f4d\u7f6e */ fos = new FileOutputStream(new File(filePath)); inputByte = new byte[1024]; System.out.println("\u5f00\u59cb\u63a5\u6536\u6570\u636e..."); while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) { fos.write(inputByte, 0, length); fos.flush(); } System.out.println("\u5b8c\u6210\u63a5\u6536\uff1a"+filePath); } finally { if (fos != null) fos.close(); if (dis != null) dis.close(); if (socket != null) socket.close(); } } catch (Exception e) { e.printStackTrace(); } } }

1.服务器端

package sterning;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
int port = 8821;

void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
// 选择进行传输的文件
String filePath = "D:\\lib.rar";
File fi = new File(filePath);

System.out.println("文件长度:" + (int) fi.length());

// public Socket accept() throws
// IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。

s = ss.accept();
System.out.println("建立socket链接");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();

DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();

int bufferSize = 8192;
byte[] buf = new byte[bufferSize];

while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}

if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意关闭socket链接哦,不然客户端会等待server的数据过来,
// 直到socket超时,导致数据不完整。
fis.close();
s.close();
System.out.println("文件传输完成");
}

} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String arg[]) {
new ServerTest().start();
}
}

2.socket的Util辅助类

package sterning;

import java.net.*;
import java.io.*;

public class ClientSocket {
private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}

/** *//**
* 创建socket连接
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
}

public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null)
out.close();
throw e;
} finally {
}
}

public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
}

public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) {

}
}
}

3.客户端

package sterning;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;

public class ClientTest {
private ClientSocket cs = null;

private String ip = "localhost";// 设置成服务器IP

private int port = 8821;

private String sendMessage = "Windwos";

public ClientTest() {
try {
if (createConnection()) {
sendMessage();
getMessage();
}

} catch (Exception ex) {
ex.printStackTrace();
}
}

private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("连接服务器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("连接服务器失败!" + "\n");
return false;
}

}

private void sendMessage() {
if (cs == null)
return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("发送消息失败!" + "\n");
}
}

private void getMessage() {
if (cs == null)
return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("接收消息缓存错误\n");
return;
}

try {
//本地保存路径,文件名会自动从服务器端继承而来。
String savePath = "E:\\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len=0;

savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();

System.out.println("文件的长度为:" + len + "\n");
System.out.println("开始接收文件!" + "\n");

while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
//下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比
System.out.println("文件接收了" + (passedlen * 100/ len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存为" + savePath + "\n");

fileOut.close();
} catch (Exception e) {
System.out.println("接收消息错误" + "\n");
return;
}
}

public static void main(String arg[]) {
new ClientTest();
}
}

java中的网络信息传输方式基于TCP协议和UD协议P的,socket是基于TCP协议的实现代码如下:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class ClientTcpSend {
public static void main(String[] args) {
int length = 0;
byte[] sendBytes = null;
Socket socket = null;
DataOutputStream dos = null;
FileInputStream fis = null;
try {
try {
socket = new Socket();
socket.connect(new InetSocketAddress("127.0.0.1", 33456),
dos = new DataOutputStream(socket.getOutputStream());
File file = new File("/root/6674541037_c3a9c8b64c_b.jpg");
Ffis = new FileInputStream(file);
sendBytes = new byte[1024];
while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
dos.write(sendBytes, 0, length);
dos.flush();
}
} finally {
if (dos != null)
dos.close();
if (fis != null)
fis.close();
if (socket != null)
socket.close();
}
} catch (Exception e) {
e.printStackTrace();

}

}

}

代码如下:

/*
import java.io.*;
import java.net.*;
import java.util.*;
*/
private HttpURLConnection connection;//存储连接
private int downsize = -1;//下载文件大小,初始值为-1
private int downed = 0;//文加已下载大小,初始值为0
private RandomAccessFile savefile;//记录下载信息存储文件
private URL fileurl;//记录要下载文件的地址
private DataInputStream fileStream;//记录下载的数据流
try{
/*开始创建下载的存储文件,并初始化值*/
File tempfileobject = new File("h:\\webwork-2.1.7.zip");
if(!tempfileobject.exists()){
/*文件不存在则建立*/
tempfileobject.createNewFile();
}
savefile = new RandomAccessFile(tempfileobject,"rw");

/*建立连接*/
fileurl = new URL("https://webwork.dev.java.net/files/documents/693/9723/webwork-2.1.7.zip");
connection = (HttpURLConnection)fileurl.openConnection();
connection.setRequestProperty("Range","byte="+this.downed+"-");

this.downsize = connection.getContentLength();
//System.out.println(connection.getContentLength());

new Thread(this).start();
}
catch(Exception e){
System.out.println(e.toString());
System.out.println("构建器错误");
System.exit(0);
}
public void run(){
/*开始下载文件,以下测试非断点续传,下载的文件存在问题*/
try{
System.out.println("begin!");
Date begintime = new Date();
begintime.setTime(new Date().getTime());
byte[] filebyte;
int onecelen;
//System.out.println(this.connection.getInputStream().getClass().getName());
this.fileStream = new DataInputStream(
new BufferedInputStream(
this.connection.getInputStream()));
System.out.println("size = " + this.downsize);
while(this.downsize != this.downed){
if(this.downsize - this.downed > 262144){//设置为最大256KB的缓存
filebyte = new byte[262144];
onecelen = 262144;
}
else{
filebyte = new byte[this.downsize - this.downed];
onecelen = this.downsize - this.downed;
}
onecelen = this.fileStream.read(filebyte,0,onecelen);
this.savefile.write(filebyte,0,onecelen);
this.downed += onecelen;
System.out.println(this.downed);
}
this.savefile.close();
System.out.println("end!");
System.out.println(begintime.getTime());
System.out.println(new Date().getTime());
System.out.println(begintime.getTime() - new Date().getTime());
}
catch(Exception e){
System.out.println(e.toString());
System.out.println("run()方法有问题!");
}
}

/***
//FileClient.java
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) throws Exception {

//使用本地文件系统接受网络数据并存为新文件

File file = new File("d:\\fmd.doc");

file.createNewFile();

RandomAccessFile raf = new RandomAccessFile(file, "rw");

// 通过Socket连接文件服务器

Socket server = new Socket(InetAddress.getLocalHost(), 3318);
//创建网络接受流接受服务器文件数据
InputStream netIn = server.getInputStream();
InputStream in = new DataInputStream(new BufferedInputStream(netIn));
//创建缓冲区缓冲网络数据

byte[] buf = new byte[2048];

int num = in.read(buf);

while (num != (-1)) {//是否读完所有数据

raf.write(buf, 0, num);//将数据写往文件

raf.skipBytes(num);//顺序写文件字节

num = in.read(buf);//继续从网络中读取文件

}
in.close();
raf.close();
}
}

//FileServer.java
import java.io.*;
import java.util.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) throws Exception {

//创建文件流用来读取文件中的数据

File file = new File("d:\\系统特点.doc");

FileInputStream fos = new FileInputStream(file);

//创建网络服务器接受客户请求

ServerSocket ss = new ServerSocket(8801);

Socket client = ss.accept();

//创建网络输出流并提供数据包装器

OutputStream netOut = client.getOutputStream();

OutputStream doc = new DataOutputStream(
new BufferedOutputStream(netOut));

//创建文件读取缓冲区

byte[] buf = new byte[2048];

int num = fos.read(buf);
while (num != (-1)) {//是否读完文件
doc.write(buf, 0, num);//把文件数据写出网络缓冲区
doc.flush();//刷新缓冲区把数据写往客户端
num = fos.read(buf);//继续从文件中读取数据
}
fos.close();
doc.close();
}
}
*/

扩展阅读:java javascript ... java serializable ... java webservice ... java@override ... java serversocket ... java zookeeper ... java ajax ... jquery mobile api ... skype free download ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网