Java Socket Multithreading

Source: Internet
Author: User

1. Server

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.*;import java.util.concurrent.*;p Ublic class Multithreadserver {private int port = 8821;private ServerSocket serversocket; Private Executorservice executorservice;//thread pool private final int pool_size = 10;//Single CPU thread pool size public multithreadserver () th Rows IOException {serversocket = new ServerSocket (port);//Runtime Availableprocessor () method returns the number of CPUs for the current system. Executorservice = Executors.newfixedthreadpool (Runtime.getruntime (). Availableprocessors () * POOL_ SIZE); SYSTEM.OUT.PRINTLN ("server Start");} public void Service () {while (true) {Socket socket = Null;try {//Receive client connection, as long as the client is connected, the accept () is triggered, thereby establishing a connection Socket = Serversocke T.accept (); Executorservice.execute (new Handler (socket));} catch (Exception e) {e.printstacktrace ();}}} public static void Main (string[] args) throws IOException {new Multithreadserver (). Service ();}} Class Handler IMPlements Runnable {Private socket socket;public Handler (socket socket) {this.socket = socket;} Private PrintWriter getwriter (socket socket) throws IOException {OutputStream socketout = Socket.getoutputstream (); return new PrintWriter (Socketout, True);} Private BufferedReader Getreader (socket socket) throws IOException {InputStream socketin = Socket.getinputstream (); return new BufferedReader (new InputStreamReader (Socketin)); public string Echo (String msg) {return "echo:" + msg;} public void Run () {try {System.out.println ("New connection accepted" + socket.getinetaddress () + ":" + socket.getport ()); B Ufferedreader br = getreader (socket); PrintWriter pw = getwriter (socket); String msg = null;while (msg = Br.readline ()) = null) {System.out.println (msg);p w.println (Echo (msg)), if (Msg.equals (" Bye ")) Break;}} catch (IOException e) {e.printstacktrace ();} finally {try {if (socket! = NULL) Socket.close ();} catch (IOException e) {E.PR Intstacktrace ();}}}

2. Client

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 class Multithreadclient {public static void main (string[] args) {int numtasks = 10; Executorservice exec = Executors.newcachedthreadpool (); for (int i = 0; i < numtasks; i++) {Exec.execute (CreateTask (i)); }}//defines a simple task private static Runnable createtask (final int taskID) {return new Runnable () {private socket socket = NULL;PR ivate int port = 8821;public void Run () {System.out.println ("Task" + TaskID + ": Start"); try {socket = new socket ("Localho St ", port);//Send Close command outputstream socketout = Socket.getoutputstream (); Socketout.write (" shutdown\r\n ". GetBytes ());// Feedback from the receiving server BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); String msg = null;while (msg = Br.readline ()) = null) System.out.println (msg); catch (IOException e) {E.prinTstacktrace ();}}};}} 


Java Socket Multithreading

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.