Simple analog multithreaded Socket Communication (Java)

Source: Internet
Author: User

Let's take a look at a single-threaded source code (with detailed comments in the code):

Server (Tcpserver.java):


Import java.net.*;
Import java.io.*;

public class tcpserver{public
  static void Main (string[] args) throws exception{serversocket
    ss = new Serversocke T (5566); Create a socket server that listens for 5566-port
    int i=0;
    Use the dead loop's Non-stop listening port while
    (true) {
      socket s = ss.accept ()///////////////////////////Accept ()
      i++;
      System.out.println ("the" + i + +) client successfully connected. ");
      DataInputStream dis = new DataInputStream (S.getinputstream ()); Gets the input stream of the client socket object and adds a layer of datainputstream pipe outside to facilitate the reading of
      the data System.out.println (Dis.readutf ()), the data in the read stream, The readUTF () method of the DataInputStream object can read the data in the stream and support the Chinese
      dis.close ();//close the pipe connection
      s.close ();//Close the socket Connection
    }
  }

}

Client (Tcpclient.java):


Import java.net.*;
Import java.io.*;

public class tcpclient{public
  static void Main (string[] args) throws exception{
    socket s = new socket ("192.168.24 .177 ", 5566); Creates a socket object that connects the 5566-Port
    dataoutputstream dos = new DataOutputStream of a server with an IP address of 192.168.24.177 (S.getoutputstream ()); Gets the output stream of the socket object, and packages a layer of dataoutputstream pipe outside to facilitate output data
    Dos.writeutf ("client Message"); writeUTF of//dataoutputstream object () Method can output data and support Chinese
    dos.flush ()//Ensure that all data has been exported
    dos.close ();//Turn off output stream s.close ();//
    Close socket Connection
  }
}


The code above uses a simple network interaction between the socket object and the ServerSocket object, that is, the client sends a message to the server through the writeUTF () method of the DataOutputStream object. The server uses the DataInputStream object's readUTF () method to read the data.

looks good, but the accept () method of the ServerSocket object is a blocking method that waits until there is a client connection.

Similarly, the readUTF () method of the DataInputStream object is also a blocking method, and it waits until the client invokes the writeUTF () method.

Therefore, if a client successfully connects to the server, but delays the writeUTF () method of sending data, the server waits until the client calls the writeUTF () method, during which the entire server is blocked and no longer accepts other client connections , which is clearly not in line with the actual situation.

To solve this problem, of course, to use multithreading.

If each client is unique to a thread, let the readUTF () method block the client's unique thread without blocking the server main thread so that the server can accept multiple client connections at the same time, regardless of when the client calls the writeUTF () method to send the data. The code is as follows:

Server (Tcpserver.java):

import java.net.*; import java.io.*; public class tcpserver{public static void Main (string[] args) throws exception{serversocket ss = new ServerSocket ( 5566);
    Create a socket server that listens for 5566-Port int i=0;
      Use the dead loop's Non-stop listening port while (true) {socket s = ss.accept ();//Use the socket server's accept () method to get the client socket object.
      i++; System.out.println ("the" + i + +) client successfully connected.
      "); Client C = new Client (i,s); Create client-side processing thread object threads t =new thread (c); Create client processing thread T.start (); Start thread}}//client processing thread class (Implementing Runnable Interface) class client implements runnable{int clientindex = 0;//Save Client ID Socket s = null;
    Save client Socket Object (int i,socket s) {clientindex = i;
  THIS.S = s;
      public void Run () {//Print out client data try{datainputstream dis = new DataInputStream (S.getinputstream ());
      System.out.println ("First" + Clientindex + "client sends a message:" + DIS.READUTF ());
      Dis.close ();
    S.close (); The catch (Exception e) {}}} 

Client (Tcpclient.java):

Import java.net.*;
Import java.io.*;

public class tcpclient{public
  static void Main (string[] args) throws exception{
    socket s = new socket ("192.168.24 .177 ", 5566); Creates a socket object that connects the 5566-Port
    dataoutputstream dos = new DataOutputStream of a server with an IP address of 192.168.24.177 (S.getoutputstream ()); Gets the output stream of the socket object and dataoutputstream the outer layer of the pipe to facilitate output data
    Thread.Sleep ((int) (Math.random () *3000)); Let the client send
    a message Dos.writeutf ("client Message") to the server at irregular intervals; the writeUTF () method of the//dataoutputstream object can output the data and support the Chinese
    dos.flush (); Ensure all data has been output
    dos.close ();//Turn off output stream
    s.close ();//close socket Connection
  }
}


The results of the operation are as follows (reference results are not necessarily the same.) ):


It is obvious that the 2nd, 3, 4 clients do not send messages to the server, but they are successfully connected, and the 2nd, 3, 4 clients send messages to the server in no order.

Multi-threading enables multiple clients to connect to the server at the same time, and the server can process messages sent by multiple clients in real time.

These are just some ideas for beginners, just for reference.

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.