Multithreaded Java Socket programming

Source: Internet
Author: User

The Java 5 executorservice is used to implement multi-threading in a thread pool, which simulates the client sending requests to the same server side.

1. Service-side

 PackageLocalsocket;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;Importjava.net.*;Importjava.util.concurrent.*; Public classMultithreadserver {Private intport=8821; PrivateServerSocket ServerSocket; PrivateExecutorservice Executorservice;//thread Pool    Private Final intpool_size=10;//single CPU thread pool size         PublicMultithreadserver ()throwsioexception{ServerSocket=NewServerSocket (port); //the runtime's Availableprocessor () method returns the number of CPUs in the current system.Executorservice=executors.newfixedthreadpool (Runtime.getruntime (). Availableprocessors () *pool_size); System.out.println ("Server Startup"); }         Public voidService () { while(true) {Socket Socket=NULL; Try {                //receiving a client connection, as long as the customer is connected, the accept () is triggered and the connection is establishedsocket=serversocket.accept (); Executorservice.execute (NewHandler (socket)); } Catch(Exception e) {e.printstacktrace (); }        }    }         Public Static voidMain (string[] args)throwsIOException {Newmultithreadserver (). Service (); }}classHandlerImplementsrunnable{Privatesocket socket;  PublicHandler (socket socket) { This. socket=socket; }    PrivatePrintWriter getwriter (Socket socket)throwsioexception{outputstream socketout=Socket.getoutputstream (); return NewPrintWriter (Socketout,true); }    PrivateBufferedReader Getreader (Socket socket)throwsioexception{InputStream Socketin=Socket.getinputstream (); return NewBufferedReader (NewInputStreamReader (Socketin)); }     Publicstring Echo (String msg) {return"Echo:" +msg; }     Public voidrun () {Try{System.out.println ("New Connection Accepted" +socket.getinetaddress () + ":" +Socket.getport ()); BufferedReader BR=Getreader (socket); PrintWriter PW=getwriter (socket); String msg=NULL;  while((Msg=br.readline ())! =NULL) {System.out.println (msg);                Pw.println (Echo (msg)); if(Msg.equals ("Bye"))                     Break; }        } Catch(IOException e) {e.printstacktrace (); }finally{            Try {                if(socket!=NULL) Socket.close (); } Catch(IOException e) {e.printstacktrace (); }        }    }}

2. Client

 PackageLocalsocket;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.net.Socket;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classmultithreadclient { Public Static voidMain (string[] args) {intNumtasks = 10; Executorservice exec=Executors.newcachedthreadpool ();  for(inti = 0; i < numtasks; i++) {Exec.execute (CreateTask (i)); }    }    //define a simple task    Private StaticRunnable CreateTask (Final intTaskID) {        return NewRunnable () {PrivateSocket socket =NULL; Private intport=8821;  Public voidrun () {System.out.println ("Task" + TaskID + ": Start"); Try{Socket=NewSocket ("localhost", Port); //Send Close CommandOutputStream socketout =Socket.getoutputstream (); Socketout.write ("Shutdown\r\n". GetBytes ()); //feedback from the receiving serverBufferedReader br =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); String msg=NULL;  while(msg = Br.readline ())! =NULL) System.out.println (msg); } Catch(IOException e) {e.printstacktrace ();    }            }        }; }}

Multithreaded Java Socket programming

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.