Client:
Packagett;ImportJava.io.DataOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.net.InetSocketAddress;ImportJava.net.Socket; Public classClienttcpsend { Public Static voidMain (string[] args) {intLength = 0; byte[] Sendbyte =NULL; Socket Socket=NULL; DataOutputStream dout=NULL; FileInputStream Fin=NULL; Try { Try{Socket=NewSocket (); Socket.connect (NewInetsocketaddress ("127.0.0.1", 33456), 10 * 1000); Dout=NewDataOutputStream (Socket.getoutputstream ()); File File=NewFile ("e:\\tu\\dscf0320. JPG "); Fin=Newfileinputstream (file); Sendbyte=New byte[1024]; Dout.writeutf (File.getname ()); while(length = Fin.read (sendbyte, 0, sendbyte.length)) >0) {dout.write (Sendbyte,0, length); Dout.flush (); } } Catch(Exception e) {}finally{ if(Dout! =NULL) Dout.close (); if(Fin! =NULL) Fin.close (); if(Socket! =NULL) Socket.close (); } } Catch(Exception e) {e.printstacktrace (); } }}
Service side:
Packagetest;ImportJava.io.DataInputStream;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classServertcplistenerImplementsRunnable {@Override Public voidrun () {} Public Static voidMain (string[] args) {Try { FinalServerSocket Server =NewServerSocket (33456); Thread th=NewThread (NewRunnable () {@Override Public voidrun () { while(true) { Try{System.out.println ("Start listening ... "); Socket Socket=server.accept (); System.out.println ("There are links"); Receivefile (socket); } Catch(Exception e) {e.printstacktrace (); } } } }); Th.run (); } Catch(Exception ex) {ex.printstacktrace (); } } Public Static voidReceivefile (Socket socket)throwsIOException {byte[] Inputbyte =NULL; intLength = 0; DataInputStream din=NULL; FileOutputStream Fout=NULL; Try{din=NewDataInputStream (Socket.getinputstream ()); Fout=NewFileOutputStream (NewFile ("e:\\" +Din.readutf ())); Inputbyte=New byte[1024]; System.out.println ("Start receiving data ..."); while(true) { if(DIN! =NULL) {length= Din.read (inputbyte, 0, inputbyte.length); } if(length = =-1) { Break; } System.out.println (length); Fout.write (Inputbyte,0, length); Fout.flush (); } System.out.println ("Complete Reception"); } Catch(Exception ex) {ex.printstacktrace (); } finally { if(Fout! =NULL) Fout.close (); if(DIN! =NULL) Din.close (); if(Socket! =NULL) Socket.close (); } }}