📜  监听TCP(1)

📅  最后修改于: 2023-12-03 14:56:27.267000             🧑  作者: Mango

监听 TCP

在网络编程中,TCP(传输控制协议)是一种常用的传输协议,用于可靠地在计算机之间传输数据。编写程序可通过监听 TCP 端口来接收和处理传入的连接请求。

以下是使用不同编程语言监听 TCP 的代码示例,供程序员参考。

Python
import socket

HOST = 'localhost'
PORT = 1234

# 创建 TCP 套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定地址和端口
server_socket.bind((HOST, PORT))

# 监听连接
server_socket.listen()

print(f"Listening on {HOST}:{PORT}...")

while True:
    # 等待客户端连接
    client_socket, addr = server_socket.accept()
    print(f"Connected to {addr[0]}:{addr[1]}")

    # 读取客户端发送的数据
    data = client_socket.recv(1024)
    print(f"Received: {data.decode()}")

    # 处理数据
    # ...

    # 发送响应
    response = "Hello, client!"
    client_socket.send(response.encode())

    # 关闭连接
    client_socket.close()

# 关闭服务器套接字
server_socket.close()
Java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpListener {

    public static void main(String[] args) {
        int port = 1234;

        try {
            // 创建服务器套接字
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Listening on port " + port + "...");

            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("Connected to " + clientSocket.getInetAddress() + ":" + clientSocket.getPort());

                // 获取输入输出流
                InputStream inputStream = clientSocket.getInputStream();
                OutputStream outputStream = clientSocket.getOutputStream();

                // 读取客户端发送的数据
                byte[] buffer = new byte[1024];
                int bytesRead = inputStream.read(buffer);
                String data = new String(buffer, 0, bytesRead);
                System.out.println("Received: " + data);

                // 处理数据
                // ...

                // 发送响应
                String response = "Hello, client!";
                outputStream.write(response.getBytes());
                outputStream.flush();

                // 关闭连接
                clientSocket.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
C#
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class TcpListenerExample {
    public static void Main() {
        int port = 1234;
        
        try {
            // 创建服务器套接字
            TcpListener serverSocket = new TcpListener(IPAddress.Any, port);
            serverSocket.Start();
            Console.WriteLine($"Listening on port {port}...");

            while (true) {
                // 等待客户端连接
                using (TcpClient clientSocket = serverSocket.AcceptTcpClient()) {
                    Console.WriteLine($"Connected to {clientSocket.Client.RemoteEndPoint}");

                    // 获取输入输出流
                    NetworkStream networkStream = clientSocket.GetStream();

                    // 读取客户端发送的数据
                    byte[] buffer = new byte[1024];
                    int bytesRead = networkStream.Read(buffer, 0, buffer.Length);
                    string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                    Console.WriteLine($"Received: {data}");

                    // 处理数据
                    // ...

                    // 发送响应
                    string response = "Hello, client!";
                    byte[] responseBytes = Encoding.ASCII.GetBytes(response);
                    networkStream.Write(responseBytes, 0, responseBytes.Length);
                    networkStream.Flush();

                    // 关闭连接
                    networkStream.Close();
                }
            }
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }
}

以上是使用 Python、Java 和 C# 监听 TCP 的代码示例。根据自己的需求和所选择的编程语言,可以参考这些示例来编写网络程序。