Java Socket-based file transmission example

Source: Internet
Author: User
Java uses the socket-based file transfer example to transmit large files over the network recently, so I have a preliminary understanding of socket-based file transmission. On the basis of a program provided by a netizen, I processed some data, used buffer input/output stream to package the output stream, and then used data input/output stream for packaging, speed up transmission. To put it bluntly, let's look at the server-side programs first. 1. server package sterning; import Java. io. bufferedinputstream; import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. file; import Java. io. fileinputstream; import java.net. serversocket; import java.net. socket; public class servertest {int Port = 8821; void start () {socket S = NULL; try {serversocket Ss = new serversocket (port); While (true) {// select the file to be transmitted string filepath = "D: \ Lib. RAR "; file Fi = new file (filepath); system. out. println ("file length:" + (INT) Fi. length (); // public socket accept () throws // ioexception listens and is connected to this socket. This method is blocked until the connection is established. S = ss. accept (); system. out. println ("establish socket link"); datainputstream Dis = new datainputstream (New bufferedinputstream (S. getinputstream (); DIS. readbyte (); datainputstream FD = new datainputstream (New bufferedinputstream (New fileinputstream (filepath); dataoutputstream PS = new dataoutputstream (S. getoutputstream (); // transmits the file name and length to the client. All platforms need to be applied here, such as processing the Chinese name. For details, see the ready-made code in think in Java 4th. 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 (FS! = NULL) {READ = FCM. read (BUF);} If (read =-1) {break;} ps. write (BUF, 0, read);} ps. flush (); // close the socket link. Otherwise, the client will wait for the server data to come over. // The data is incomplete until the socket times out. Fiis. close (); S. close (); system. out. println ("file transfer completed") ;}} catch (exception e) {e. printstacktrace () ;}} public static void main (string Arg []) {New servertest (). start () ;}} 2. socket util auxiliary class package sterning; import java.net. *; import Java. io. *; public class clientsocket {private string IP; private int port; private Socket socket = NULL; dataoutputstream out = NULL; datainputstream getmessagestream = NULL; Public clientsocket (string IP, int port) {This. IP = IP; this. port = port;}/*** // *** create a socket connection ** @ throws exception */Public void createconnection () throws exception {try {socket = new socket (IP, Port);} catch (exception e) {e. printstacktrace (); If (socket! = NULL) socket. close (); throw E;} finally {} public void sendmessage (string sendmessage) throws exception {try {out = new dataoutputstream (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 ();} el Se {out. writeutf (sendmessage); Out. Flush () ;}} catch (exception e) {e. printstacktrace (); If (OUT! = NULL) out. close (); throw E;} finally {} public datainputstream getmessagestream () throws exception {try {getmessagestream = new datainputstream (New bufferedinputstream (socket. getinputstream (); Return getmessagestream;} catch (exception e) {e. printstacktrace (); If (getmessagestream! = NULL) getmessagestream. Close (); throw E;} finally {} public void shutdownconnection () {try {If (OUT! = NULL) Out. Close (); If (getmessagestream! = NULL) getmessagestream. Close (); If (socket! = NULL) socket. close () ;}catch (exception e) {}} 3. client package sterning; import Java. io. bufferedoutputstream; import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. fileoutputstream; public class clienttest {private clientsocket cs = NULL; private string IP = "localhost"; // set it to the server IP private int Port = 8821; private string sendmessage = "windwos "; public clienttest () {try {I F (createconnection () {sendmessage (); getmessage () ;}} catch (exception ex) {ex. printstacktrace () ;}} private Boolean createconnection () {cs = new clientsocket (IP, Port); try {CS. createconnection (); system. out. print ("connection to the server successful! "+" \ N "); Return true;} catch (exception e) {system. Out. Print (" failed to connect to the server! "+" \ N "); Return false ;}} private void sendmessage () {If (cs = NULL) return; try {CS. sendmessage (sendmessage);} catch (exception e) {system. out. print ("failed to send message! "+" \ N ") ;}} private void getmessage () {If (cs = NULL) return; datainputstream inputstream = NULL; try {inputstream = cs. getmessagestream ();} catch (exception e) {system. out. print ("received message cache error \ n"); return;} Try {// Local save path. The file name is automatically inherited from the server. 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 fileoutputstream (savepath); Len = inputstream. readlong (); system. out. println ("file length:" + Len + "\ n"); system. out. println ("start receiving files! "+" \ N "); While (true) {int READ = 0; If (inputstream! = NULL) {READ = inputstream. read (BUF);} passedlen + = read; If (read =-1) {break;} // The following progress bar is based on prograssbar of the graphic interface. If it is a file, some identical percentages may be printed again. out. println ("the file received" + (passedlen * 100/Len) + "% \ n"); fileout. write (BUF, 0, read);} system. out. println ("received successfully, the file is 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 ();}} this implements the process of sending files from the server to the client. Of course, the opposite is true. slightly different. the details of cross-platform are not implemented in the Code. Sometimes, you can provide them to interested users.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.