Socket introduction and using Java to realize socket communication

1. Socket overview

        Socket (socket) is a mechanism used to realize network communication in computer network programming. It provides a programming interface that allows applications to transmit data over the network to achieve communication between different hosts.

        Socket can be regarded as an abstract concept used to describe the endpoint of network communication. It contains various parameters and status information required for communication, so that applications can send and receive data through it.

The main features of Socket include the following aspects:

  1. Communication protocol: Socket can transmit data based on different communication protocols, such as TCP/IP, UDP, etc.
  2. Communication model: Socket can support different communication models, such as connection-oriented streaming Socket (such as TCP) and connectionless datagram Socket (such as UDP).
  3. Client-Server Model: Socket is usually used to implement client-server model, where client application communicates with server through Socket.
  4. Port number: Socket identifies the communication port of the application through the port number, so that different applications can communicate on the same host at the same time.
  5. API interface: Socket provides a set of API interfaces for applications to perform Socket programming, including operations such as establishing a connection, sending data, receiving data, and closing a connection.

        Socket programming can be carried out in different programming languages, such as C, C++, Java, Python, etc., by calling the corresponding Socket API to realize the network communication function. In Socket programming, the following steps are usually involved:

  1. Create Socket: Use Socket API to create a Socket object, specify the protocol type and communication mode.
  2. Bind port: Bind the Socket to the local IP address and port number.
  3. Listening for connection requests (only on the server side): For the server side, call the Socket API to monitor the connection requests from the client.
  4. Establish a connection (client only): For the client, call the Socket API to establish a connection with the server.
  5. Data transmission: send and receive data through Socket.
  6. Close connection: After the communication ends, close the Socket connection.

        Socket programming can be used in various network applications, such as Web servers, mail servers, chat applications, games, etc. It provides a flexible, reliable and efficient way for applications to communicate over networks.

2. Java implements socket communication

1. Use TCP connection

Using TCP communication, it java.net.Socketcreates an Socketobject using . SocketClass is typically used for TCP communication.

(1) Server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        try {
            // 创建ServerSocket对象,指定监听的端口号
            ServerSocket serverSocket = new ServerSocket(12345);

            System.out.println("等待客户端连接...");

            // 监听客户端的连接请求
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端已连接");

            // 获取输入流和输出流 输入流和输出流是通过socket对象来进行数据传输的。
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            String message;

            while (true) {
                // 读取客户端发送的信息
                message = in.readLine();

                if (message.equalsIgnoreCase("exit")) {
                    // 如果接收到终止标志,退出循环
                    break;
                }

                System.out.println("收到客户端消息:" + message);

                // 发送响应给客户端
                out.println("已收到你的消息:" + message);
            }

            // 关闭连接
            clientSocket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

(2) client

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
    public static void main(String[] args) {
        try {
            // 创建Socket对象,指定服务端的IP地址和端口号
            Socket socket = new Socket("127.0.0.1", 12345);

            // 获取输入流和输出流 输入流和输出流是通过socket对象来进行数据传输的。
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            // 从控制台读取用户输入
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String message;

            while (true) {
                System.out.println("请输入要发送的信息(输入 'exit' 退出):");
                message = reader.readLine();

                if (message.equalsIgnoreCase("exit")) {
                    // 如果用户输入 'exit',发送终止标志给服务端并退出循环
                    out.println("exit");
                    break;
                }

                // 将用户输入的信息发送给服务端
                out.println(message);

                // 接收服务端的响应并打印
                String response = in.readLine();
                System.out.println("服务端响应:" + response);
            }

            // 关闭连接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Test Results:

 2. Use UDP connection

Using UDP communication, java.net.DatagramSocketan object is created using DatagramSocket. DatagramSocketClasses are typically used for UDP communication.

(1) Server

package socket.UDP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public class UDPClient {
    public static void main(String[] args) {
        try {
            // 创建DatagramSocket对象
            DatagramSocket socket = new DatagramSocket();

            InetAddress serverAddress = InetAddress.getByName("127.0.0.1");
            int serverPort = 12345;

            // 从控制台读取用户输入
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String message;

            while (true) {
                System.out.println("请输入要发送的信息(输入 'exit' 退出):");
                message = reader.readLine();

                if (message.equalsIgnoreCase("exit")) {
                    // 如果用户输入 'exit',退出循环
                    break;
                }

                byte[] sendData = message.getBytes();

                // 创建发送数据的DatagramPacket对象
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, serverPort);

                // 发送数据
                socket.send(sendPacket);

                byte[] receiveData = new byte[1024];

                // 创建接收数据的DatagramPacket对象
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收服务端的响应
                socket.receive(receivePacket);

                // 将接收到的数据转换为字符串并打印
                String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("服务端响应:" + response);
            }

            // 关闭Socket连接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

(2) client

package socket.UDP;

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

public class UDPServer {
    public static void main(String[] args) {
        try {
            // 创建DatagramSocket对象,并指定监听的端口号
            DatagramSocket socket = new DatagramSocket(12345);
            System.out.println("等待客户端连接...");

            byte[] receiveData = new byte[1024];

            while (true) {
                // 创建接收数据的DatagramPacket对象
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收客户端发送的数据
                socket.receive(receivePacket);

                // 获取客户端的IP地址和端口号
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                // 将接收到的数据转换为字符串
                String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("收到客户端消息:" + message);

                if (message.equalsIgnoreCase("exit")) {
                    // 如果接收到终止标志,退出循环
                    break;
                }

                // 构造发送数据的字节数组
                String response = "已收到你的消息:" + message;
                byte[] sendData = response.getBytes();

                // 创建发送数据的DatagramPacket对象
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);

                // 发送响应给客户端
                socket.send(sendPacket);
            }

            // 关闭Socket连接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Test Results:

 

Guess you like

Origin blog.csdn.net/weixin_49561506/article/details/131554978