Java multithreading realizes the communication _java between server side and multi-client

Source: Internet
Author: User
Tags flush readline socket

The Java language constructs a network server, realizes the communication between the client and the server, realizes the client to have the independent thread, does not interfere with each other.

The basic steps of using multithreading to realize communication between server and multithreading

    1. Server-side Create ServerSocket, loop call accept () Wait for client link
    2. Client creates a socket and requests and server-side links
    3. The server side accepts the client request, creates the Socekt and establishes a special line link with the client
    4. Create a linked socket to talk on a separate thread
    5. The server continues to wait for the new link

Server-Side Server.java

Package test.concurrent.socket; 
Import java.io.*; 
Import java.net.InetAddress; 
Import Java.net.ServerSocket; 
 
Import Java.net.Socket; 
 /** * Created by Dong on 15-6-22. 
      * Socket communication based on TCP protocol, implement user login * Server side/public class Server {public static void main (string[] args) {try { 
      1, create a server-side socket, that is, ServerSocket, specify the bound port, and listen to this port serversocket serversocket = new ServerSocket (8888); 
      Socket socket = NULL; 
      Record the number of clients int count = 0; 
      SYSTEM.OUT.PRINTLN ("* * * server is about to start, waiting for the link of the client * * *);" 
        Loop listening for a link waiting for a client while (true) {//calling the Accept () method to start listening, waiting for the client's link socket = serversocket.accept (); 
        To create a new thread serverthread Serverthread = the newer serverthread (socket); 
 
        Start thread Serverthread.start (); count++; 
        Count the number of clients System.out.println ("Number of clients:" + count); 
        InetAddress address = socket.getinetaddress (); 
 SYSTEM.OUT.PRINTLN ("Current client IP:" + address.gethostaddress ());     } catch (IOException e) {e.printstacktrace (); 
 } 
  } 
}

Server thread processing class Serverthread.java

Package test.concurrent.socket; 
Import java.io.*; 
 
Import Java.net.Socket; 
 /** * Created by Dong on 15-6-22. 
  * Server thread processing class/public class Serverthread extends thread {//The socket socket socket that is associated with this threading = null; 
  Public serverthread (socket socket) {this.socket = socket; 
    //A thread performs an action that responds to the client's request public void run () {InputStream is = null; 
    InputStreamReader ISR = null; 
 
    BufferedReader br = null; 
    OutputStream OS = null; 
    PrintWriter pw = null; 
      try {//get an input stream and read the client's information is = Socket.getinputstream (); ISR = new InputStreamReader (IS); Bytes are converted to character streams br = new BufferedReader (ISR); 
      Add buffer String info = null; 
      The loop reads the data while (info = Br.readline ())!= null) {System.out.println ("I am the server, the client says:" +info); } socket.shutdowninput (); 
      Turn off input stream/get output stream, respond to client request OS = Socket.getoutputstream (); PW = new PrintWriter (OS); 
     Packaging for print stream pw.write ("Welcome"); Pw.flush (); 
    Will cache output} catch (IOException e) {e.printstacktrace (); 
          }finally {try {//close resource if (PW!= null) pw.close (); 
          if (OS!= null) os.close (); 
          if (is!= null) is.close (); 
          if (ISR!= null) isr.close (); 
          if (br!= null) br.close (); 
        if (socket!= null) socket.close (); 
 
        catch (IOException e) {e.printstacktrace (); 
 } 
 
    } 
 
 
 
  } 
}

Client Client.java

Package test.concurrent.socket; 
Import java.io.*; 
 
Import Java.net.Socket; 
 /** * Created by Dong on 15-6-22. * Client/public class client {public static void main (string[] args) {try {//1, create client socket, specify server side 
      Slogan and address socket socket = new socket ("localhost", 8888); 2, get the output stream, send information to the server outputstream OS = Socket.getoutputstream (); BYTE output stream PrintWriter pw = new PrintWriter (OS); Wraps the output stream as a print stream pw.write (user name: Tom; 
      Password: 456 "); 
      Pw.flush (); Socket.shutdownoutput (); 
      Closes the output stream InputStream is = Socket.getinputstream (); 
      InputStreamReader ISR = new InputStreamReader (IS); 
 
      BufferedReader br = new BufferedReader (ISR); 
      String info = null; 
      Loop read while (info = Br.readline ())!= null) {System.out.println ("I am a client: Server says:" + info); 
      } br.close (); 
      Is.close (); 
 
 
      Isr.close (); 
      Pw.close (); 
      Os.close (); 
    Socket.close (); catch (IOException e) {e.printstacktrace (); 
 } 
  } 
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.