欢迎来到天天文库
浏览记录
ID:6042996
大小:50.00 KB
页数:7页
时间:2017-12-31
《文件传输(基于socket编程)》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、服务器端:packagesterning;importjava.io.BufferedInputStream;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.net.ServerSocket;importjava.net.Socket;publicclassServerTest{intport=8821;voidstart(){Sockets=n
2、ull;try{ServerSocketss=newServerSocket(port);while(true){//选择进行传输的文件StringfilePath="D:lib.rar";Filefi=newFile(filePath);System.out.println("文件长度:"+(int)fi.length());//publicSocketaccept()throws//IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。s=ss.accept();System.out.println("建立
3、socket链接");DataInputStreamdis=newDataInputStream(newBufferedInputStream(s.getInputStream()));dis.readByte();DataInputStreamfis=newDataInputStream(newBufferedInputStream(newFileInputStream(filePath)));DataOutputStreamps=newDataOutputStream(s.getOutputStream());//将文件名及长度传给
4、客户端。这里要真正适用所有平台,例如中文名的处理,//还需要加工,具体可以参见ThinkInJava4th里有现成的代码。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.wr
5、ite(buf,0,read);}ps.flush();//注意关闭socket链接哦,不然客户端会等待server的数据过来,//直到socket超时,导致数据不完整。fis.close();s.close();System.out.println("文件传输完成");}}catch(Exceptione){e.printStackTrace();}}publicstaticvoidmain(Stringarg[]){newServerTest().start();}}2.sooket的Util类packagesterning;imp
6、ortjava.net.*;importjava.io.*;publicclassClientSocket{privateStringip;privateintport;privateSocketsocket=null;DataOutputStreamout=null;DataInputStreamgetMessageStream=null;publicClientSocket(Stringip,intport){this.ip=ip;this.port=port;}/***//***创建socket连接**@throwsExcepti
7、on*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.getO
8、utputStream());if(sendMessage.equals("Windows")){out.writeByte(0x1);out.flush();return;}if(sendMessage.
此文档下载收益归作者所有