那些年的 网络通信之 TCP/IP 传输控制协议 ip 加 端口 客户端上传文件到服务器端服务器端返回上传成功消息
多线程开启, 客户端通过 Socket 流 上传文件到服务端的一个小程序练习.
1. 抓住阻塞式方法,去调试
2. 获取对应流对象操作对应的对象 这时候自己不能懵,一定要清晰,最好命名就能区别,一搞混了就乱了
import java.io.*; import java.net.*; class UpLoadDemo{ public static void main(String [] args) throws Exception{ int port=10085; String ipAddr="192.168.20.1"; String srcFilePath="C:\\Users\\Ghc\\Desktop\\psb.jpg"; String destFilePath="C:\\Users\\Ghc\\Desktop\\test\\psb2.jpg"; new Thread(new UploadServer(new ServerSocket(port),destFilePath)).start(); new Thread(new UploadClient(new Socket(ipAddr,port),srcFilePath)).start(); } } class UploadClient implements Runnable{ private Socket socket; private BufferedInputStream socketBufIn,fileBufIn; private BufferedOutputStream socketBufOut; private String filePath; private int len=-1; private byte [] buf=new byte[1024]; UploadClient(Socket socket,String filePath){ this.socket=socket; this.filePath=filePath; } public void run(){ try{ fileBufIn=new BufferedInputStream(new FileInputStream(filePath)); socketBufIn=new BufferedInputStream(socket.getInputStream()); socketBufOut=new BufferedOutputStream(socket.getOutputStream()); while((len=fileBufIn.read(buf))!=-1){ socketBufOut.write(buf,0,len); socketBufOut.flush(); } socket.shutdownOutput(); len=socketBufIn.read(buf); System.out.println("server: "+new String(buf,0,len)); } catch(Exception e){ e.printStackTrace(); } finally{ if(fileBufIn!=null) try{ fileBufIn.close(); fileBufIn=null; } catch(Exception e){ e.printStackTrace(); } if(socket!=null) try{ socket.close(); socket=null; } catch(Exception e){ e.printStackTrace(); } } } } class UploadServer implements Runnable{ private ServerSocket serverSocket; private Socket socket; private String destFilePath; private BufferedInputStream socketBufIn; private BufferedOutputStream socketBufOut; private BufferedOutputStream fileBufOut; private int len=-1; private byte[] buf=new byte[1024]; UploadServer(ServerSocket serverSocket,String destFilePath){ this.serverSocket=serverSocket; this.destFilePath=destFilePath; } public void run(){ try{ fileBufOut=new BufferedOutputStream(new FileOutputStream(destFilePath)); socket=serverSocket.accept(); socketBufIn=new BufferedInputStream(socket.getInputStream()); socketBufOut=new BufferedOutputStream(socket.getOutputStream()); System.out.println("ip: "+socket.getInetAddress().getHostAddress()+"connected!"); while((len=socketBufIn.read(buf))!=-1){ fileBufOut.write(buf,0,len); fileBufOut.flush(); } socketBufOut.write("File uploaded Successfully! ".getBytes()); socketBufOut.flush(); //socket.shutdownInput(); } catch(Exception e){ e.printStackTrace(); } finally{ if(fileBufOut!=null) try{ fileBufOut.close(); fileBufOut=null; } catch(Exception e){ e.printStackTrace(); } if(serverSocket!=null) try{ serverSocket.close(); } catch(Exception e){ e.printStackTrace(); } } } }
效果图:
如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。