Java implements an example of socket continuously fetching messages from the server

  • 2020-04-01 03:20:43
  • OfStack

The server we use simulation software, is a very small software, download software NetAssist: (link: http://xiazai.jb51.net/201403/tools/NetAssist (jb51.net). Rar)

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201404/20140428114231.jpg? 2014328114743 ">

The second step is to paste the code of our client:


import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

public class Client {  
    public static final String IP_ADDR = "192.168.3.65";//Server address & NBSP;  
    public static final int PORT = 8080;//Server port number & NBSP;    
    static String text = null;

 public static void main(String[] args) throws IOException {    
        System.out.println(" Client boot ..."); 
        Socket socket = null;  
        socket = new Socket(IP_ADDR, PORT);    
        while (true) {    
            try {  
                //Creates a flow socket and connects it to the specified port number & NBSP; on the specified host.
                //Read server-side data & NBSP;    
                DataInputStream input = new DataInputStream(socket.getInputStream());    

    byte[] buffer;
    buffer = new byte[input.available()];
    if(buffer.length != 0){
    System.out.println("length="+buffer.length);
    //Read buffer
    input.read(buffer);
    //Convert string
    String three = new String(buffer);
    System.out.println(" content =" + three);
    }
            } catch (Exception e) {  
                System.out.println(" Client exception :" + e.getMessage());   
            } 
        }    
    }
} 

You can see the print result as follows:
Length represents the length of the message


 Client boot ...
length=27
 content =//www.jb51.net

Ok, we are done with a socket client, which can always receive messages from the server.


Related articles: