Java Multithreading for multi-client socket communication

Source: Internet
Author: User
Tags readline

First, the service side

 PackageCom.czhappy.hello.socket;Importjava.io.IOException;Importjava.net.InetAddress;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classServer { Public Static voidMain (string[] args) {//Create ServerSocket example, specify port, listen        Try{serversocket ServerSocket=NewServerSocket (8888); System.out.println ("Service is about to start, waiting for client to connect"); //log the number of clients            intCount = 0; Socket Socket=NULL;  while(true){                //start listening, waiting for the client to connectSocket =serversocket.accept (); Serverthread Serverthread=Newserverthread (socket);                Serverthread.start (); Count++; System.out.println ("Number of clients =" +count); InetAddress Address=socket.getinetaddress (); System.out.println ("The IP address of the current client is:" +address.gethostaddress ()); }        } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}
 PackageCom.czhappy.hello.socket;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;Importjava.io.UnsupportedEncodingException;ImportJava.net.Socket;/*** Server thread processing class *@authorAdministrator **/ Public classServerthreadextendsthread{Socket Socket=NULL;  PublicServerthread (socket socket) { This. Socket =socket; }         Public voidrun () {InputStream is=NULL; InputStreamReader ISR=NULL; BufferedReader BR=NULL; OutputStream OS=NULL; PrintWriter PW=NULL; Try {            //get byte input streamis =Socket.getinputstream (); //flow byte input to character input streamISR =NewInputStreamReader (IS, "Utf-8"); //adding buffering for character input streamsBR =NewBufferedReader (ISR); String Data=Br.readline ();  while(data!=NULL) {System.out.println ("I am the server," said the client, "+data); Data=Br.readline (); }            //close the input streamSocket.shutdowninput (); //gets the output stream in response to a client requestOS =Socket.getoutputstream (); PW=Newprintwriter (OS); Pw.write ("Welcome you!" ");        Pw.flush (); } Catch(unsupportedencodingexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{            Try {                if(pw!=NULL) {pw.close (); }                if(os!=NULL) {os.close (); }                if(br!=NULL) {br.close (); }                if(isr!=NULL) {isr.close (); }                if(is!=NULL) {is.close (); }                if(socket!=NULL) {socket.close (); }            } Catch(IOException e) {e.printstacktrace (); }        }            }}

Second, the client

 PackageCom.czhappy.hello.socket;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.net.UnknownHostException; Public classClient { Public Static voidMain (string[] args) {Try {            //Create a client socket, specify the server address and PortSocket socket =NewSocket ("192.168.0.45", 8888); //get output stream, send message to serverOutputStream OS = Socket.getoutputstream ();//byte output streamPrintWriter PW =NewPrintWriter (OS);//wrapping the output stream as a print streamPw.write ("username: admin; password: 123");            Pw.flush (); Socket.shutdownoutput ();//turn off the output stream//get input stream, read server-side response informationInputStream is =Socket.getinputstream (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (IS)); String Data=Br.readline ();  while(data!=NULL) {System.out.println ("I am the client, the server says:" +data); Data=Br.readline ();            } br.close ();            Is.close ();            Pw.close ();            Os.close ();        Socket.close (); } Catch(unknownhostexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }        }

Third, test results

You need to start the server before you start the client

Server Run Results:

Client Run Results:

Java Multithreading for multi-client socket communication

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.