浅析Java基于Socket的文件传输案例
本文实例介绍了Java基于Socket的文件传输案例,分享给大家供大家参考,具体内容如下
1、Java代码
packagecom.wf.demo.socket.socketfile; importjava.net.*; importjava.io.*; /** *2.socket的Util辅助类 * *@authorwillson * */ 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){ } } }
2、Java代码
packagecom.wf.demo.socket.socketfile; importjava.io.BufferedInputStream; importjava.io.DataInputStream; importjava.io.DataOutputStream; importjava.io.File; importjava.io.FileInputStream; importjava.net.ServerSocket; importjava.net.Socket; /** *1.服务器端 * *@authorwillson * */ publicclassServerTest{ intport=8821; voidstart(){ Socketsocket=null; try{ ServerSocketserverSocket=newServerSocket(port); while(true){ //选择进行传输的文件 StringfilePath="E:\\lib.zip"; Filefi=newFile(filePath); System.out.println("FileName:"+fi.getName()+";\tFileSize():"+(int)fi.length()+"bytes"); //publicSocketaccept()throws //IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。 System.out.println("等待客户端连接,连接端口:"+port); socket=serverSocket.accept(); System.out.println("建立socket链接"); DataInputStreamdis=newDataInputStream(newBufferedInputStream(socket.getInputStream())); dis.readByte(); DataInputStreamfis=newDataInputStream(newBufferedInputStream(newFileInputStream(filePath))); DataOutputStreamps=newDataOutputStream(socket.getOutputStream()); //将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见ThinkInJava //4th里有现成的代码。 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(); //注意关闭socket链接哦,不然客户端会等待server的数据过来, //直到socket超时,导致数据不完整。 fis.close(); socket.close(); System.out.println("文件传输完成\n"); } }catch(Exceptione){ e.printStackTrace(); } } publicstaticvoidmain(Stringarg[]){ newServerTest().start(); } }
3、客户端
packagecom.wf.demo.socket.socketfile; importjava.io.BufferedOutputStream; importjava.io.DataInputStream; importjava.io.DataOutputStream; importjava.io.FileOutputStream; /** *3.客户端 * *@authorwillson * */ publicclassClientTest{ privateClientSocketcs=null; privateStringip="localhost";//设置成服务器IP privateintport=8821; privateStringsendMessage="Windwos"; publicClientTest(){ try{ if(createConnection()){ sendMessage(); getMessage("F:\\"); } }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(StringsavePath){ if(cs==null) return; DataInputStreaminputStream=null; try{ inputStream=cs.getMessageStream(); }catch(Exceptione){ System.out.print("接收消息缓存错误\n"); return; } try{ //本地保存路径,文件名会自动从服务器端继承而来。 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("FileSize():"+len+"bytes"); 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(); } }
希望本文所述对大家学习java程序设计有所帮助。