Use Socket to realize the echo server of UDP version


insert image description here

1. Introduction to Socket

Socket (Java Socket) is a set of classes and interfaces provided by the Java programming language for network communication. It is based on the Socket programming interface and provides a simple and powerful way to implement network applications.

The socket class library provides a wealth of methods and functions for handling all aspects of network communication. It supports both TCP and UDP protocols, enabling reliable, connection-oriented communication (TCP) or unreliable, connectionless communication (UDP). Java Socket also provides some advanced functions, such as multi-thread processing, asynchronous communication, encrypted communication, etc., to meet the needs of different network applications.

This article mainly uses Socket to implement the UDP version of the client and server

  • DatagramSocket Is a UDP Socket for sending and receiving UDP datagrams.

  • DatagramPacketIt is the datagram sent and received by UDP Socket.

2. DatagramSocket

DatagramSocket is a class used to implement the UDP protocol in Java network programming. It is a subclass based on the Socket class for sending and receiving UDP datagrams.

The constructor of DatagramSocket:

method illustrate
DatagramSocket() Create a UDP datagram socket socket, bind any random port of this machine (general user client)
DatagramSocket(int port) Create a UDP data socket socket, bind the specified port port (generally used for the server)

Common methods of DatagramSocket are as follows:

method illustrate
void receive(DatagramPacket p) Receive a datagram from this socket, if no datagram is received, it will block and wait
void send(DatagramPacket p) Send a packet from this socket
void close() close datagram socket

3. DatagramPacket

DatagramPacket is a class used to encapsulate and parse UDP datagrams (Datagram) in Java network programming. It is used to send and receive UDP datagrams in DatagramSocket

The construction method of DatagramPacket:

method illustrate
DatagramPacket(byte[] buf, int length) Construct a DatagramPacket to receive the datagram, the received data is stored in the byte array (the first parameter buf), and the specified length is received (the second parameter length)
DatagramPacket(byte[] buf, int offset, int length, SocketAddress address) Construct a DatagramPacket to send datagrams. The sent data is a byte array (the first parameter buf), from 0 to the specified length (the second parameter length). address specifies the IP and port number of the destination host

Common methods of DatagramPacket:

method illustrate
InetAddress getAddress() Obtain the IP address of the sending host from the received datagram; or obtain the IP address of the receiving host from the sent datagram
int getPort() Get the port number of the sending host from the received datagram; or get the port number of the receiving host from the sent datagram
byte[] getData() Get the data in the datagram

4. InetSocketAddress

InetSocketAddress is a class used to represent IP addresses and port numbers in Java network programming. It is a subclass of the SocketAddress class and is used to specify the address and port of the host in network communication.

Briefly introduce the construction method of InetSocketAddress:

InetSocketAddress(InetAddress addr,int port) Create a Socket address, including IP address and port number

5. Implement the UDP version of the echo server

Echo Server (Echo Server) is a simple web server application that receives the data sent by the client and returns the received data to the client as it is.

Client code:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    
    
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
    
    
        socket = new DatagramSocket(serverPort);
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
    
    
        System.out.println("客户端上线!");
        Scanner scanner = new Scanner(System.in);

        while (true) {
    
    
            // 读取用户输入的内容
            System.out.println("-> ");
            String request = scanner.next();
            // 构造 UDP请求,并发送给服务器
            DatagramPacket reqPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(this.serverIp), this.serverPort);
            socket.send(reqPacket);

            // 从服务器读取响应
            DatagramPacket respPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(respPacket);
            String resp = new String(respPacket.getData(), 0, respPacket.getLength());
        }
    }

    public static void main(String[] args) throws IOException {
    
    
        UdpEchoClient echoClient = new UdpEchoClient("127.0.0.1", 6666);
        echoClient.start();
    }
}

Server code:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    
    
    private DatagramSocket socket = null;

    // port 为服务器要绑定的端口
    public UdpEchoServer(int port) throws SocketException {
    
    
        socket = new DatagramSocket(port);
    }

    /**
     * 服务器启动方法
     */
    public void start() throws IOException {
    
    
        System.out.println("服务器启动!");
        while (true) {
    
    
            // 读取请求并解析
            DatagramPacket reqPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(reqPacket);
            // 解析请求
            String req = new String(reqPacket.getData(), 0, reqPacket.getLength());
            // 计算响应
            String resp = process(req);
            // 将响应返回给客户端
            DatagramPacket respPacket = new DatagramPacket(resp.getBytes(), resp.getBytes().length,
                    reqPacket.getSocketAddress());
            socket.send(respPacket);
            // 打印日志
            System.out.printf("[%s:%d] req: %s;resp: %s\n", reqPacket.getSocketAddress().toString(),
                    reqPacket.getPort(), req, resp);
        }
    }

    /**
     * 根据请求计算响应
     * 因为是 回显服务器,直接返回即可
     *
     * @param req
     */
    private String process(String req) {
    
    
        return req;
    }

    public static void main(String[] args) throws IOException {
    
    
        UdpEchoServer echoServer = new UdpEchoServer(6666);
        echoServer.start();
    }
}

Running process:
insert image description here

operation result:

insert image description here

insert image description here

In addition, the server provides servers for multiple clients. IDEA cannot start multiple clients by default, so manually set

insert image description here

insert image description here

insert image description here

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/m0_63463510/article/details/132104067