Java Implementation Socket Client connection service side _java

Source: Internet
Author: User
Tags getmessage readline server port

This example only does simple function demonstration, the code is not rigorous, only explains how the client realizes the connection service side simple code.

The code tests the compilation run environment under the integrated Eclipse tool as shown in the following illustration:

Client Echoclient.java Code:

Package Com.zhengzz.echo;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import Java.net.Socket;

Import java.net.UnknownHostException;
  
  Class echoc{private socket socket;
    Public Echoc () {//TODO auto-generated constructor stub try {socket = new socket ("localhost", 60000);
    catch (Unknownhostexception e) {e.printstacktrace ();
    catch (IOException e) {e.printstacktrace (); The public void Client () {try {bufferedreader br = new BufferedReader (new InputStreamReader) (Socket.geti
      Nputstream ()));
      PrintWriter pw = new PrintWriter (Socket.getoutputstream (), true);
      
      BufferedReader LBR = new BufferedReader (new InputStreamReader (system.in));
      String linestr = null;
        
        while ((Linestr = Lbr.readline ())!= null) {pw.println (LINESTR);
        
        System.out.println (Br.readline ()); if (linestr.Equals ("bye#")) {break;
    A catch (IOException e) {e.printstacktrace ()); }} public class Echoclient {public static void main (string[] args) {new Echoc ().
  Client (); }

}

Server-side Echoserver.java code:

Package Com.zhengzz.echo;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;

Import Java.net.Socket;
  
  Class echos{private ServerSocket serversocket;
    Public Echos () {try {serversocket = new ServerSocket (60000);
    catch (IOException e) {e.printstacktrace ();
        
        public void Server () {while (true) {try {socket socket = serversocket.accept ();

        SYSTEM.OUT.PRINTLN ("Client:" + socket.getinetaddress () + ":" + socket.getlocalport ());
        BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

        PrintWriter pw = new PrintWriter (Socket.getoutputstream (), true);

        String Linestr;

          while ((Linestr = Br.readline ())!= null) {System.out.println (LINESTR);

        PW.PRINTLN ("--->" + linestr);
  } catch (IOException e) {      System.out.println ("Disconnected: ("); }}} public class Echoserver {public static void main (string[] args) {new Echos ().
  Server (); }

}

I debug the results directly under the Eclipse tool as follows:

Let's look at a helloword-level Java Socket communication example. Communication process:

Start the Server end and go to a dead loop to listen for connection requests on a port. Then run the client side, clients issue the connection request, the service supervisor hears this request to send back to the client to receive the message, the connection establishes, initiates a thread to process this request, then continues the dead loop to listen to other requests. The client enters a string and presses the ENTER key to send data to the server. The server responds to client data after reading the data. This request was processed and the thread that started died. If the client receives a return data other than "OK", sends the connection request again and sends the data, the server starts a thread again for this connection to respond ... The client exits until the return data received by the client is "OK".

Service-Side Source code:

Package com.defonds.socket.begin; 
Import Java.io.BufferedReader; 
Import Java.io.DataInputStream; 
Import Java.io.DataOutputStream; 
Import Java.io.InputStreamReader; 
Import Java.net.ServerSocket; 
 
Import Java.net.Socket;  
    public class Server {public static final int port = 12345;//Listener port number public static void main (string[] args) {  
    SYSTEM.OUT.PRINTLN ("Server startup ... \ n");  
    Server server = new server ();  
  Server.init ();  
      public void Init () {try {serversocket serversocket = new ServerSocket (PORT);  
        while (true) {//Once there is a blockage, it means that the server and the client have a connection Socket client = Serversocket.accept ();  
      Handle this connection new Handlerthread (client);  
    The catch (Exception e) {System.out.println ("Server exception:" + E.getmessage ());  
    } Private class Handlerthread implements Runnable {private socket socket;  
      Public Handlerthread (socket client) {socket = client; New threAD (This). Start (); public void Run () {try {//Read client data DataInputStream input = new DataInputStream (so 
        Cket.getinputstream ()); String clientinputstr = Input.readutf ()//This is to note that the write method of the client output stream corresponds, otherwise it throws the Eofexception//process client data SYSTEM.OUT.PR  
  
        INTLN ("Client sent over the content:" + clientinputstr);  
        Reply to client information dataoutputstream out = new DataOutputStream (Socket.getoutputstream ());  
        System.out.print ("Please enter: \ t");  
        A line of String s = new BufferedReader (new InputStreamReader (system.in)) that sends keyboard input. ReadLine ();  
         
        Out.writeutf (s);  
        Out.close ();  
      Input.close ();  
      catch (Exception e) {System.out.println ("Server Run Exception:" + E.getmessage ());  
          finally {if (socket!= null) {try {socket.close ();  
            catch (Exception e) {socket = null; SYSTEM.OUT.PRINTLN ("service-side finally exception:" + E.getmessaGE ());  
 }  
        }  
      }  
    }  
  }  
}

Client source code:

Package com.defonds.socket.begin; 
Import Java.io.BufferedReader; 
Import Java.io.DataInputStream; 
Import Java.io.DataOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStreamReader; 
 
Import Java.net.Socket; public class Client {public static final String ip_addr = "localhost";/server address public static final int PORT = 12345  
    ;//server port number public static void main (string[] args) {System.out.println ("Client startup ...");  
    SYSTEM.OUT.PRINTLN ("The client terminates \ n" When the server-side character is received \ "Ok\"); 
      while (true) {socket socket = NULL;  
          
        try {//Create a stream socket and connect it to the specified port number on the specified host socket = new socket (ip_addr, PORT);  
        Read server-side data datainputstream input = new DataInputStream (Socket.getinputstream ());  
        Send data to server side dataoutputstream out = new DataOutputStream (Socket.getoutputstream ());  
        System.out.print ("Please enter: \ t");  
 String str = new BufferedReader (new InputStreamReader (system.in)). ReadLine ();       Out.writeutf (str);   
        String ret = Input.readutf ();  
        SYSTEM.OUT.PRINTLN ("Server-side return is:" + ret);  
          Disconnect if (ok. Equals (ret)) {SYSTEM.OUT.PRINTLN ("Client closes connection") If "OK" is received;  
          Thread.Sleep (500);  
        Break 
        } out.close (); 
      Input.close ();  
      catch (Exception e) {System.out.println ("Client exception:" + E.getmessage ()); 
          finally {if (socket!= null) {try {socket.close ();  
            catch (IOException e) {socket = null;  
          SYSTEM.OUT.PRINTLN ("Client finally exception:" + E.getmessage ());  

 } 
        } 
      } 
    }  
  }  
}

        Note: When the Socket output stream Write data method is writeUTF, the input stream reads the relevant data using READUTF. Otherwise, the eofexception exception will be thrown.

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.