Client:
Public class client {private int Port = 8000; private string host = "localhost"; private Socket socket; Public client () throws unknownhostexception, ioexception {socket = new socket (host, port);} public void readfromuser () throws ioexception {bufferedreader BR = new bufferedreader (New inputstreamreader (system. in); string line; while (line = BR. readline ())! = NULL) {If (line. equals ("bye") {socket. close (); system. out. println ("Close socket"); break;} Send (line) ;}} public void send (string MSG) throws ioexception {printwriter PW = new printwriter (socket. getoutputstream (), true); PW. println (MSG);} public static void main (string ARGs []) throws unknownhostexception, ioexception {new client (). readfromuser ();}}
Server:
Public class server {private int Port = 8000; private serversocket; private executorservice; private final int pool_size = 4; public server () throws ioexception {serversocket = new serversocket (port, 2); // create the thread pool executorservice = executors. newfixedthreadpool (runtime. getruntime (). availableprocessors () * pool_size); system. out. println ("server startup ..... "+" Initial thread count: "+ runtime. getruntime (). availableprocessors () * pool_size);} public void Service () throws ioexception {int COUNT = 0; while (true) {Socket socket = serversocket. accept (); system. out. println (++ count + "Client Connected"); // new thread (New handler(socket)).start(commandid executorservice.exe cute (new handler (socket ));}} public static void main (string ARGs []) throws ioexception {new server (). service ();} private Cl Ass handler implements runnable {private Socket socket; Public handler (Socket socket) {This. socket = socket;} public void run () {try {handle ();} catch (ioexception e) {e. printstacktrace () ;}} private void handle () throws ioexception {bufferedreader BR = new bufferedreader (New inputstreamreader (socket. getinputstream (); string line; while (line = BR. readline ())! = NULL) {If (line. equals ("goodbye") {socket. close (); serversocket. close (); break;} system. out. println ("from" + socket. getport () + ":" + line );}}}}
The server uses the JDK built-in thread pool to process concurrent requests.
You can also use NiO to implement non-blocking communication.