posted on 2007-10-13 09:11
诗特林 阅读(91220)
评论(49) 所属分类:
socket
java基于socket文件传输示例
最近需要进行网络传输大文件,于是对基于socket的文件传输作了一个初步的了解。在一位网友提供的程序基础上,俺进行了一些加工,采用了缓冲输入/输出流来包装输出流,再采用数据输入/输出输出流进行包装,加快传输的速度。废话少说,先来看服务器端的程序。
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();
}
}
这就实现了从服务器端向客户端发送文件的过程,当然,反过来,也一样.稍有不同.代码中对跨平台的细节没有实现,有时间或兴趣的朋友可以提供一下.