Click to enter _ more _java thousand ask
1, how to write multi-threaded socket program
Find out what the socket looks for here: what the socket is
A multithreaded socket is similar to a single thread, only using a multithreaded approach to manage connections, the main thread is responsible for receiving connections, creating new threads when connected, and each thread is responsible for communicating with its clients.
Learn about single threaded sockets look here: How to write a single multithreaded socket program
Compared with the single-threaded socket example, the server can communicate with more than one client, but the frequent creation and destruction of multithreading can lead to significant resource overhead, and the network resources of the system are limited. As a result, a thread pool is generally introduced, which can be reused to some extent, reducing the number of threads created and destroyed to reduce overhead.
Our code is also divided into two parts: client and server. The server-side code contains two ways to use and not to use the thread pool.
Service-Side code:
ImportJava.io.BufferedReader;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors; Public class socketthreadpooldemoserver { Private intPort =8000;PrivateServerSocket ServerSocket;PrivateExecutorservice Executorservice;//Connection pool Private Final intPool_size =1;//Connection pool size, if 1 o'clock supports up to 2 threads Public Socketthreadpooldemoserver()throwsException {ServerSocket =NewServerSocket (port); Executorservice = Executors.newfixedthreadpool (Runtime.getruntime (). Availableprocessors () * POOL_SIZE);//Initialize thread poolSystem.out.println ("waitting connet ..."); }/** * * Accept connection * * @author Sunjie at June 14, 2016 * * * Public void Service() {Socket socket =NULL; while(true) {Try{socket = serversocket.accept (); Executorservice.execute (NewHandler (socket));//Using connection pooling //New Thread (new Handler (socket)). Start ();//Do not use connection pooling}Catch(IOException e) {E.printstacktrace (); } } }/** * * Thread class, responsible for maintaining communication with a client * * @author Sunjie at June 14, 2016 * * *Class Handler implements Runnable {PrivateSocket socket =NULL; Public Handler(Socket socket) { This. socket = socket; }@Override Public void Run() {System.out.println ("New Connection accepted:"+ socket.getinetaddress () +":"+ Socket.getport ());Try{BufferedReader reader =NewBufferedReader (NewInputStreamReader (Socket.getinputstream (),"UTF-8")); PrintWriter writer =NewPrintWriter (Socket.getoutputstream ()); String msg =NULL; while(msg = Reader.readline ())! =NULL) {System.out.println ("from"+ socket.getinetaddress () +":"+ socket.getport () +", receive msg:"+ msg); WRITER.PRINTLN (msg); Writer.flush ();if("Close". Equals (msg)) { Break; } } }Catch(IOException e) {E.printstacktrace (); }finally{Try{if(Socket! =NULL) {socket.close (); } }Catch(IOException e) {E.printstacktrace (); } } } } Public Static void Main(string[] args)throwsException {NewSocketthreadpooldemoserver (). Service (); }}
After the service-side code is run, the program listens until a client request is received. The results are as follows:
Waitting connet ...
Client code (exactly the same as a single thread):
Public classsocketdemoclient {PrivateString host ="127.0.0.1";//IP to be sent to the server Private intPort =8000;//port to be sent to the server PrivateSocket socket; Public socketdemoclient() throws Exception {socket =NewSocket (host, Port);//construct the socket client and connect to the server} Public void Talk() throws IOException {Try{BufferedReader reader =NewBufferedReader (NewInputStreamReader (Socket.getinputstream (),"UTF-8")); PrintWriter writer =NewPrintWriter (Socket.getoutputstream ());//Read the local console messageBufferedReader Localreader =NewBufferedReader (NewInputStreamReader (System.inch)); String msg =NULL; while(msg = Localreader.readline ())! =NULL) {writer.println (msg); Writer.flush (); System. out. println ("Send msg:"+ Reader.readline ());if("Close". Equals (msg)) { Break; } } }Catch(Exception e) {E.printstacktrace (); }finally{if(Socket! =NULL) {socket.close (); } } } Public Static void Main(string[] args) throws Exception {NewSocketdemoclient (). talk (); }}
Since we are testing multiple clients to connect to the same server, we need to run the client code multiple times. Here we run two times (called Client 1, Client 2), to view the server console, the following results will appear, indicating that the connection has been successful:
Waitting connet ...
New Connection accepted:/127.0.0.1:59593
New Connection accepted:/127.0.0.1:59596
We're going to enter the message we want to send in the console of client 1, "maintain world peace", after the carriage return is determined, the following result is present in the console of client 1, the message has been sent:
Send msg: Maintaining world Peace
Then go to the console of the client 2, enter "good study day Up", the return to determine, the Client 2 console has the following results, the message has been issued:
Send msg: Study well
In the console of the server, we will see the following results, indicating that two client messages have been accepted:
Waitting connet ...
New Connection accepted:/127.0.0.1:59593
New Connection accepted:/127.0.0.1:59596
from/127.0.0.1:59593, receive msg: Safeguarding World Peace
from/127.0.0.1:59596, receive msg: study well
Java thousand ask _02 basic use (012) _ How to write multi-threaded socket program