Simple simulation of multi-thread socket communication (Java)

Source: Internet
Author: User


First, let's look at the original code of a single thread.Code(The Code has detailed comments ):

 

Server (tcpserver. Java ):

Import java.net. *; import Java. io. *; public class tcpserver {public static void main (string [] ARGs) throws exception {serversocket Ss = new serversocket (5566); // create a socket server, listen to port 5566 int I = 0; // use the endless listening port while (true) {socket S = ss. accept (); // use the accept () method of the socket server to obtain the client socket object. I ++; system. Out. println ("no." + I + "Client Connected successfully! "); Datainputstream Dis = new datainputstream (S. getinputstream (); // obtain the input stream of the client socket object, and add a layer of datainputstream pipeline outside to facilitate reading the data system. out. println (DIS. readutf (); // read the data in the stream. The readutf () method of the datainputstream object can read the data in the stream and support the Chinese dis. close (); // close the MPs queue connection S. close (); // close the socket connection }}}

Client (tcpclient. Java ):

 
Import java.net. *; import Java. io. *; public class tcpclient {public static void main (string [] ARGs) throws exception {socket S = new socket ("192.168.24.177", 5566); // create a socket object, port 5566 of the server whose IP address is 192.168.24.177, dataoutputstream dos = new dataoutputstream (S. getoutputstream (); // get the output stream of the socket object, and package a layer of dataoutputstream pipeline on the outer side to facilitate the output of DOS data. writeutf ("client message"); // The writeutf () method of the dataoutputstream object can output data and support Chinese dos. flush (); // make sure all data has been output to dos. close (); // close the output stream S. close (); // close the socket connection }}

The above Code uses the socket object and serversocket object for simple network interaction, that is, the client sends a message to the server through the writeutf () method of the dataoutputstream object, and the server uses the readutf () of the datainputstream object () method to read data.

It looks good, but the accept () method of the serversocket object is a blocking method, it will wait until there is a client connection.

Similarly, the readutf () method of the datainputstream object is also a blocking method, and it will wait until the client calls the writeutf () method.

Therefore, if a client successfully connects to the server but does not call the writeutf () method to send data, the server will wait until the client calls the writeutf () method, during this period, the entire server is blocked and cannot accept connections from other clients. Obviously, this is not in line with the actual situation.

To solve this problem, multithreading is required.

If each client has a unique thread, the readutf () method will block the unique thread of the client rather than the main thread of the server. In this way, the server can accept connections from multiple clients at the same time, instead of considering when the client calls the writeutf () method to send data. The Code is as follows:

 

Server (tcpserver. Java ):

 Import java.net. *; import Java. io. *; public class tcpserver {public static void main (string [] ARGs) throws exception {serversocket Ss = new serversocket (5566); // create a socket server, listen to port 5566 int I = 0; // use the endless listening port while (true) {socket S = ss. accept (); // use the accept () method of the socket server to obtain the client socket object. I ++; system. Out. println ("no." + I + "Client Connected successfully! "); Client c = new client (I, S); // create a client to process the thread object thread t = new thread (c); // create a client to process the thread t. start (); // start thread }}// client processing Thread class (implementing the runnable interface) class client implements runnable {int clientindex = 0; // save Client ID socket S = NULL; // save client socket object client (int I, socket s) {clientindex = I; this. S = s;} public void run () {// print the client data try {datainputstream Dis = new datainputstream (S. getinputstream (); system. out. println ("Number" + clientindex + "client sends a message:" + dis. readutf (); DIS. close (); S. close () ;}catch (exception e) {}}


Client (tcpclient. Java ):

Import java.net. *; import Java. io. *; public class tcpclient {public static void main (string [] ARGs) throws exception {socket S = new socket ("192.168.24.177", 5566); // create a socket object, port 5566 of the server whose IP address is 192.168.24.177, dataoutputstream dos = new dataoutputstream (S. getoutputstream (); // get the output stream of the socket object, and package a layer of dataoutputstream pipeline on the outer side to conveniently output the data thread. sleep (INT) (math. random () * 3000); // enables the client to send messages to the server DoS from time to time. writeutf ("client message"); // The writeutf () method of the dataoutputstream object can output data and support Chinese dos. flush (); // make sure all data has been output to dos. close (); // close the output stream S. close (); // close the socket connection }}


The running result is as follows (the reference results are not necessarily the same !) :

Obviously, the 2nd, 3, and 4 clients did not send messages to the server, but all of them were connected successfully, and the 2nd, 3, and 4 clients sent messages to the server in no order.

Multi-threading enables multiple clients to connect to the server at the same time, and the server can process messages sent by multiple clients in real time.

The above are just some ideas for beginners and are for reference only!

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.