In fact, the client and server communication is the same reason, are through the input and output of the two streams, then the implementation of file upload is the same, the client read the file to the file stream, the server file stream to accept, and then write to a file, this way to achieve the file upload, file copy is the same reason ~, See the code implementation as follows:
Client:
Packagecom.seven.tcp;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.Socket; Public classtcpfileuploadclient { Public Static voidMain (string[] args)throwsException {Socket Socket=NewSocket ("127.0.0.1", 10001); FileInputStream FIS=NewFileInputStream (NewFile ("E:\\test.txt")); OutputStream out=Socket.getoutputstream (); byte[] buf =New byte[1024]; intLen = 0; while((Len=fis.read (BUF))!=-1) {out.write (BUF); } socket.shutdownoutput (); InputStream in=Socket.getinputstream (); Len=In.read (BUF); System.out.println ("Return:" +NewString (buf,0, Len)); Fis.close (); Socket.close (); } }
Service side:
Packagecom.seven.tcp;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket;/*** Service side to use multi-threaded to achieve, so as to enable multiple users simultaneously upload * *@authorSeven **/ Public classTcpfileuploadserver { Public Static voidMain (string[] args)throwsException {serversocket serversocket=NewServerSocket (10001); //loops, opening a new thread each time a new connection is opened while(true) {Socket Socket=serversocket.accept (); NewThread (NewFileuploadthread (socket)). Start (); } }}classFileuploadthreadImplementsRunnable {Privatesocket socket; PublicFileuploadthread (Socket s) { This. Socket =s; } //implementing file uploads in the Run method Public voidrun () {Try{System.out.println (Socket.getinetaddress (). Gethostaddress ()+ ".... Connected"); String filename=socket.getinetaddress (). gethostaddress (); intCount = 1; File File=NewFile ("e:\\" + filename +count); while(File.exists ()) {file=NewFile ("e:\\" + filename + count++); } FileOutputStream FileOutputStream=Newfileoutputstream (file); InputStream in=Socket.getinputstream (); byte[] B =New byte[1024]; intLen = 0; while(len = In.read (b))! =-1) {Fileoutputstream.write (b,0, Len); } //return SuccessOutputStream out =Socket.getoutputstream (); Out.write ("Success!". GetBytes ()); Socket.close (); }Catch(Exception e) {e.printstacktrace (); Throw NewRuntimeException (e); } }}
Java Network Programming (7)--using TCP for file uploads