Multithreaded Java Socket Programming example

Source: Internet
Author: User

Package Org.merit.test.socket;import Java.io.bufferedreader;import java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.PrintWriter; Import Java.net.Socket; Public classHandler implements runnable{Privatesocket socket;  PublicHandler (socket socket) { This. socket=socket; }    Privateprintwriter getwriter (socket socket) throws ioexception{OutputStream socketout=Socket.getoutputstream (); return NewPrintWriter (Socketout,true); }    PrivateBufferedReader Getreader (socket socket) throws ioexception{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 (); }        }    }}


Package Org.merit.test.socket;import Java.io.bufferedreader;import java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.net.socket;import Java.util.concurrent.executorservice;import java.util.concurrent.Executors; Public classmultithreadclient { Public Static voidMain (string[] args) {intNumtasks =Ten; Executorservice exec=Executors.newcachedthreadpool ();  for(inti =0; i < numtasks; i++) {Exec.execute (CreateTask (i)); }    }    //define a simple task    Private StaticRunnable CreateTask (finalintTaskID) {        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 ();    }            }        }; }}
Package Org.merit.test.socket;import java.io.ioexception;import java.net.serversocket;import java.net.Socket; Import Java.util.concurrent.executorservice;import java.util.concurrent.Executors; Public classMultithreadserver {Private intPort =8821; PrivateServerSocket ServerSocket; PrivateExecutorservice Executorservice;//thread Pool    PrivateFinalintPool_size =Ten;//single CPU thread pool size     PublicMultithreadserver () throws IOException {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) throws IOException {Newmultithreadserver (). Service (); }}

Multithreaded Java Socket Programming example

Multithreaded Java Socket Programming example

Related Article

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.