Recently need to network transfer large files, so the socket-based file transfer made a preliminary understanding. On the basis of a user-provided program, I have done some processing, using buffered input/output stream to package the output stream, and then use the data input/output stream for packaging, speed up the transmission. Talk less, first look at the server-side program.
1. Server-side
PackageLocalsocket;importJava.io.bufferedinputstream;importJava.io.datainputstream;importJava.io.dataoutputstream;importJava.io.file;importJava.io.fileinputstream;importJava.net.serversocket;importJava.net.socket;public classservertest {int port = 8821; voidStart () {Socket s = null; Try{ServerSocket SS = newServerSocket (port); while (true{//Select file to transfer String FilePath = "D:\\lib.rar"; File fi = newFile (FilePath); System.out.println ("File Length:" + (int) fi.length ()); Public socket Accept () throws//IOException listens for and accepts connections to this socket. This method is blocked until the connection is made.s =Ss.accept (); SYSTEM.OUT.PRINTLN ("Establish socket link"); DataInputStream dis = new DataInputStream (newBufferedinputstream (S.getinputstream ())); Dis.readbyte (); DataInputStream fis = new DataInputStream (New Bufferedinputstream (newFileInputStream (FilePath)); DataOutputStream PS = new DataOutputStream (S.getoutputstream ());//pass the file name and length to the client. Here to really apply to all platforms, such as Chinese name processing, but also need to process, in particular, see think in Java 4th has ready-made code. Ps.writeutf (Fi.getname ()); Ps.flush (); Ps.writelong ((Long) fi.length ()); Ps.flush (); int buffersize = 8192 ; byte[] buf = new byte[buffersize]; while (true) {int read = 0; if (FIS! = null) {read = fis.read (buf ); } if (read = =-1) {break;} ps.write (buf, 0, read);} ps.flush ();//Note close the socket link Oh, or the client waits for the data from the server. The data is not complete until the socket expires. fis.close (); S.close (); System.out.println ("File transfer complete");}} Catch (Exception e) {e.printstacktrace ();}} public static void Main (String arg[]) {new servertest (). STA RT (); }}
Util Auxiliary class for 2.socket
PackageLocalsocket;import java.net.*; Import java.io.*;p Ublic ClassClientsocket {PrivateString IP; private intPort Private SOCKET socket = NULL; DataOutputStream out = null; DataInputStream Getmessagestream = null; Public clientsocket (String IP, intPort) {This.ip =ip This.port =Port }/** * Create socket connection * * @throws Exception * Exception */public void createconnection () throwsException {Try{socket = newSocket (IP, port); } catch(Exception e) {e.printstacktrace (); if (socket! = NULL) Socket.close (); ThrowE } finally{}} public void SendMessage (String sendMessage) 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 ( Exception e) {e.printstacktrace (); if (out! = null ) out.close (); throw e;} finally {}} public DataIn Putstream Getmessagestream () throws Exception {try {getmessagestream = new DataInputStream (New Buffer Edinputstream (Socket.getinputstream ())); return Getmessagestream;} catch (Exception e) {e.printstacktrace (); if (getmessagestream! = null ) Getm Essagestream.close (); Throw e;} finally {}} public void shutdownconnection () {try {if (out! = null ) out.close (); if (Getmessagestream! = null ) getmessagestream.close (); if (socket! = NULL ) Socket.close ();} catch (Exc Eption e) {}}
3. Client
PackageLocalsocket;importJava.io.bufferedoutputstream;importJava.io.datainputstream;importJava.io.dataoutputstream;importJava.io.fileoutputstream;public classclienttest {private Clientsocket CS = null; Private String IP = "localhost";//Set as server IP private int port = 8821; Private String sendMessage = "Windwos"; PublicClienttest () {try{if(CreateConnection ()) {sendMessage (); GetMessage ();} } catch(Exception ex) {Ex.printstacktrace ();} } Private BooleanCreateConnection () {cs = newClientsocket (IP, port); Try{cs. CreateConnection (); System.out.print ("Connection server succeeded!" + "\ n"); return True; } catch(Exception e) {System.out.print ("Connection Server failed!" + "\ n")); return False; }} private voidSendMessage () {if (cs = = null) return; Try{cs.sendmessage (sendMessage);} Catch(Exception e) {System.out.print ("Send message failed!" + "\ n")); }} private voidGetMessage () {if (cs = = null) return; DataInputStream InputStream = null; Try{InputStream =Cs.getmessagestream (); } catch(Exception e) {System.out.print ("receive message cache error \ n"); Return; } try{//local save path, file name is automatically inherited from server side. String Savepath = "e:\\"; int buffersize = 8192; byte[] buf = new byte[BufferSize]; int Passedlen = 0; Long len=0; Savepath + =Inputstream.readutf (); DataOutputStream fileout = new DataOutputStream (new Bufferedoutputstream (New BufferedoutputstreamFileOutputStream (Savepath))); Len = Inputstream.readlong (); System.out.println ("File length:" + len + "\ n"); System.out.println ("Start receiving file!" + "\ n"); while (true) {int read = 0; if (inputstream! = null) {read = I Nputstream.read (BUF); } Passedlen + = read; if (read =-1) {break;}//The following progress bar is Prograssbar for the graphical interface, where if you are hitting a file, you may be repeating some of the same percentage of System. Out.println ("File Received" + (Passedlen * 100/len) + "%\n"); Fileout.write (buf, 0, read);} SYSTEM.OUT.PRINTLN ("Receive completed, File saved as" + Savepath + "\ n"); Fileout.close ();} catch (Exception e) {System.out.println ( "Receive message Error" + "\ n"); return;}} public static void Main (String arg[]) {new clienttest ();}}
Java socket-based file transfer example