An example of Java implementing simple Socket communication

  • 2021-09-05 00:07:53
  • OfStack

Directory 1. Transport layer protocol
2. TCP sample
2.1 Example Effect
2.2 Server Side Program Code 3. UDP Example
3.1 Server Code 3.2 Client Code

Java socket encapsulates the implementation details of the transport layer, and developers can implement the application layer based on socket. This article introduces the simple usage of Java and socket.

1. Transport layer protocol

The transport layer includes two protocols, TCP (Transmission Control Protocol, Transmission Control Protocol) and UDP (User Datagram Protocol, User Datagram Protocol).

TCP is a connection-oriented, reliable streaming protocol. The communication parties need to establish TCP connection before "sending-receiving" data, and then communicate by sending binary data streams to each other. The so-called connection refers to the proprietary and virtual communication lines established by various devices, lines or applications communicating in the network in order to transmit messages to each other. Once Connection 1 is established, the communicating application only uses the virtual communication line to send and receive data. TCP also needs to handle end-to-end flow control.

UDP is a connectionless, unreliable datagram protocol. The sender does not need to establish a connection with the receiver, and the communication parties communicate by sending one independent datagram.

TCP ensures the reliability of transmission through serial number, confirmation and response, data verification and other mechanisms, and is suitable for scenarios requiring reliable data transmission. Application layer protocols HTTP and FTP are based on TCP. UDP has no complex control mechanism, no error correction, no retransmission, no guarantee of data accuracy, and no guarantee of data reaching its destination; However, UDP costs less traffic to transmit the same amount of data, and is suitable for scenes with high delay requirements but low accuracy requirements, such as video and audio communication.

There are three socket classes in Java, java. net. Socket and java. net. ServerSocket are based on TCP, and java. net. DatagramSocket is based on UDP.

2. TCP sample

TCP is connection-oriented, so the sender (client) needs to connect to the receiver (server) before communicating. The client uses new Socket ("localhost", 9090) to create a socket to the server, which connects to port 9090 of the host localhost.

ServerSocket implements server-side socket, and creates an instance of listening port 9090 through new ServerSocket (9090); The ServerSocket. accept () method blocks the connection of the waiting client and returns an Socket instance of the server once a connection comes in. When the connection is established, the client Socket instance and the server Socket instance can send data to the input and output stream.

2.1 Example Effect

The client program receives the content input from the console, and sends it to the server every time the client console inputs one line. After the server receives the message, it prints the message to the console.

When the client enters "Bye", the client disconnects from the server, the client program exits, and the server program continues to wait for the connection.

Client console input and output:


$ java Server.java
Bind Port 9090
New client connected.
Received Message --> Are you OK!

Server-side console output:


$ java Client.java
Are you OK!
Send Msg --> Are you OK!
Bye
$

2.2 Server-side program code


import java.net.*;
import java.io.*;

class Server {
 
 public static void main(String[] args) {
  // ServerSocket  Realized  AutoCloseable  Interface, so support  try-with-resource  Statement 
  //  Create 1 A  ServerSocket , listening  9090  Port 
  try(ServerSocket serv = new ServerSocket(9090)){
   System.out.printf("Bind Port %d\n", serv.getLocalPort());
   Socket socket = null;
   while(true){
    //  Receives a connection, and if there is no connection, accept()  Method blocks 
    socket = serv.accept();
    
    //  Gets the input stream and uses the  BufferedInputStream  And  InputStreamReader  Decoration, convenient to deal with in the form of character stream, convenient 1 Line reading content 
    try(BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()) )){
     String msg = null;
     char[] cbuf = new char[1024];
     int len = 0;
     while( (len = in.read(cbuf, 0, 1024)) != -1 ){ //  Loop to read the contents of the input stream 
      msg = new String(cbuf, 0, len);
      if("Bye".equals(msg)) { //  If detected  "Bye"  The loop jumps out and the contents of the input stream are no longer read. 
       break;
      }
      System.out.printf("Received Message --> %s \n", msg);
     }
    }catch (IOException e){
     e.printStackTrace();
    }
    
   }
   
  }catch (IOException e){
   e.printStackTrace();
  }
 }
}
2.3  Client program code 
import java.net.*;
import java.io.*;
import java.util.*;

class Client{
 
 public static void main(String[] args){
  
  try(Socket socket = new Socket("localhost", 9090)){
   BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
   Scanner scanner = new Scanner(System.in);
   scanner.useDelimiter("\r\n");
   String msg = null;
   while( !(msg = scanner.next()).equals("Bye") ){
    System.out.printf("Send Msg --> %s \n", msg);
    out.write(msg);
    out.flush(); //  Send immediately, otherwise you need to accumulate to 1 Fixed size talent 1 Secondary transmission 
   }
  }catch (IOException e){
   e.printStackTrace();
  }
  
 }
 
}

3. UDP sample

UDP does not need a connection, and the client and server communicate by sending datagrams. In Java, java. net. DatagramSocket is used to represent the UDP client or server socket, and java. net. DatagramPacket is used to represent the UDP datagram. Client and server can send datagram directly to each other without connection.

The following code implements the same function as the above program based on UDP. However, messages may fail, and some messages may not reach the server.

3.1 Server-side program code


import java.net.*;
import java.io.*;

class Server {
 
 public static void main(String[] args){
  
  //  Create 1 A  DatagramPacket  Instance, which is used to receive the  UDP  Datagram, this instance can be reused. 
  byte[] buf = new byte[8192]; //  Buffer area 
  int len = buf.length;  //  The size of the cache to be utilized 
  DatagramPacket pac = new DatagramPacket(buf, len);
  
  //  To create a server-side socket, you need to specify the bound port number 
  try(DatagramSocket serv = new DatagramSocket(9191)){
   
   while(true){
    serv.receive(pac); //  Receive datagram. If no datagram is sent, it will block 
    System.out.println("Message --> " + new String(pac.getData(), 0, pac.getLength()));
   }
   
  }catch (IOException e){
   e.printStackTrace();
  }
 }
 
}

3.2 Client Program Code


import java.io.*;
import java.net.*;
import java.util.*;

class Client {
 public static void main(String[] args){
  
  //  Create 1 Client's  UDP  Socket, you don't need to specify any information 
  try(DatagramSocket client = new DatagramSocket()){
   
   //  Create 1 Datagram instances, data and length will be reset before sending, so it is directly set to  0  That's enough.  
   //  Because it is the sender, it is necessary to set the address and port of the server 
   DatagramPacket pac = new DatagramPacket(new byte[0], 0, InetAddress.getByName("localhost"), 9191);
   
   //  Scan console input 
   Scanner scanner = new Scanner(System.in);
   scanner.useDelimiter("\r\n");
   String msg = null;
   while( !(msg = scanner.next()).equals("Bye") ){
    //  Set the data to send 
    pac.setData(msg.getBytes()); 
    //  Send Datagram 
    client.send(pac);
    System.out.println("Sent Message --> " + msg);
   }
  }catch (IOException e){
   e.printStackTrace();
  }
  
 }
}

It should be noted that UDP is connectionless, but API of DatagramSocket provides a method with the word connect, and connect here does not mean connection in TCP. Instead, it specifies that the current UDP socket can only send datagrams to the specified host and port.

The above is the Java implementation simple Socket communication example details, more about Java implementation Socket communication information please pay attention to other related articles on this site!


Related articles: