Java基于Socket文件传输示例AnBeer工作室.docx
《Java基于Socket文件传输示例AnBeer工作室.docx》由会员分享,可在线阅读,更多相关《Java基于Socket文件传输示例AnBeer工作室.docx(8页珍藏版)》请在冰豆网上搜索。
Java基于Socket文件传输示例AnBeer工作室
Java基于Socket文件传输示例2007-10-15来自:
lizhe1985 [收藏到我的网摘]
来源:
诗特林-sterning-BlogJava
最近需要进行网络传输大文件,于是对基于socket的文件传输作了一个初步的了解。
在一位网友提供的程序基础上,俺进行了一些加工,采用了缓冲输入/输出流来包装输出流,再采用数据输入/输出输出流进行包装,加快传输的速度。
废话少说,先来看服务器端的程序。
1.服务器端
packagesterning;
importjava.io.BufferedInputStream;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
import.ServerSocket;
import.Socket;
publicclassServerTest{
intport=8821;
voidstart(){
Sockets=null;
try{
ServerSocketss=newServerSocket(port);
while(true){
StringfilePath="D:
\\lib.rar";
Filefi=newFile(filePath);
System.out.println("文件长度:
"+(int)fi.length());
s=ss.accept();
System.out.println("建立socket链接");
DataInputStreamdis=newDataInputStream(newBufferedInputStream(s.getInputStream()));
dis.readByte();
DataInputStreamfis=newDataInputStream(newBufferedInputStream(newFileInputStream(filePath)));
DataOutputStreamps=newDataOutputStream(s.getOutputStream());
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long)fi.length());
ps.flush();
intbufferSize=8192;
byte[]buf=newbyte[bufferSize];
while(true){
intread=0;
if(fis!
=null){
read=fis.read(buf);
}
if(read==-1){
break;
}
ps.write(buf,0,read);
}
ps.flush();
fis.close();
s.close();
System.out.println("文件传输完成");
}
}catch(Exceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(Stringarg[]){
newServerTest().start();
}
}
2.socket的Util辅助类
packagesterning;
import.*;
importjava.io.*;
publicclassClientSocket{
privateStringip;
privateintport;
privateSocketsocket=null;
DataOutputStreamout=null;
DataInputStreamgetMessageStream=null;
publicClientSocket(Stringip,intport){
this.ip=ip;
this.port=port;
}
/***//**
*创建socket连接
*
*@throwsException
*exception
*/
publicvoidCreateConnection()throwsException{
try{
socket=newSocket(ip,port);
}catch(Exceptione){
e.printStackTrace();
if(socket!
=null)
socket.close();
throwe;
}finally{
}
}
publicvoidsendMessage(StringsendMessage)throwsException{
try{
out=newDataOutputStream(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(Exceptione){
e.printStackTrace();
if(out!
=null)
out.close();
throwe;
}finally{
}
}
publicDataInputStreamgetMessageStream()throwsException{
try{
getMessageStream=newDataInputStream(newBufferedInputStream(socket.getInputStream()));
returngetMessageStream;
}catch(Exceptione){
e.printStackTrace();
if(getMessageStream!
=null)
getMessageStream.close();
throwe;
}finally{
}
}
publicvoidshutDownConnection(){
try{
if(out!
=null)
out.close();
if(getMessageStream!
=null)
getMessageStream.close();
if(socket!
=null)
socket.close();
}catch(Exceptione){
}
}
}
3.客户端
packagesterning;
importjava.io.BufferedOutputStream;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.FileOutputStream;
publicclassClientTest{
privateClientSocketcs=null;
privateStringip="localhost";//设置成服务器IP
privateintport=8821;
privateStringsendMessage="Windwos";
publicClientTest(){
try{
if(createConnection()){
sendMessage();
getMessage();
}
}catch(Exceptionex){
ex.printStackTrace();
}
}
privatebooleancreateConnection(){
cs=newClientSocket(ip,port);
try{
cs.CreateConnection();
System.out.print("连接服务器成功!
"+"\n");
returntrue;
}catch(Exceptione){
System.out.print("连接服务器失败!
"+"\n");
returnfalse;
}
}
privatevoidsendMessage(){
if(cs==null)
return;
try{
cs.sendMessage(sendMessage);
}catch(Exceptione){
System.out.print("发送消息失败!
"+"\n");
}
}
privatevoidgetMessage(){
if(cs==null)
return;
DataInputStreaminputStream=null;
try{
inputStream=cs.getMessageStream();
}catch(Exceptione){
System.out.print("接收消息缓存错误\n");
return;
}
try{
//本地保存路径,文件名会自动从服务器端继承而来。
StringsavePath="E:
\\";
intbufferSize=8192;
byte[]buf=newbyte[bufferSize];
intpassedlen=0;
longlen=0;
savePath+=inputStream.readUTF();
DataOutputStreamfileOut=newDataOutputStream(newBufferedOutputStream(newBufferedOutputStream(newFileOutputStream(savePath))));
len=inputStream.readLong();
System.out.println("文件的长度为:
"+len+"\n");
System.out.println("开始接收文件!
"+"\n");
while(true){
intread=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(Exceptione){
System.out.println("接收消息错误"+"\n");
return;
}
}
publicstaticvoidmain(Stringarg[]){
newClientTest();
}
}
这就实现了从服务器端向客户端发送文件的过程,当然,反过来,也一样.稍有不同.代码中对跨平台的细节没有实现,有时间或兴趣的朋友可以提供一下.