c#

c# tcplistener如何创建

小樊
83
2024-11-20 03:19:06
栏目: 编程语言

在C#中,您可以使用TcpListener类创建一个TCP监听器

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

class TcpListenerExample
{
    static void Main(string[] args)
    {
        // 设置监听的IP地址和端口号
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        int port = 8080;

        // 创建一个TcpListener实例
        TcpListener listener = new TcpListener(ipAddress, port);

        // 开始监听连接
        listener.Start();
        Console.WriteLine("TCP Listener started on {0}", ipAddress + ":" + port);

        try
        {
            while (true)
            {
                // 等待客户端连接
                Console.Write("Waiting for a client connection...");
                TcpClient client = listener.AcceptTcpClient();
                Console.WriteLine("Client connected!");

                // 处理客户端请求
                HandleClientRequest(client);

                // 关闭客户端连接
                client.Close();
                Console.WriteLine("Client disconnected.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
        finally
        {
            // 停止监听
            listener.Stop();
            Console.WriteLine("TCP Listener stopped.");
        }
    }

    static void HandleClientRequest(TcpClient client)
    {
        // 读取客户端发送的数据
        NetworkStream stream = client.GetStream();
        byte[] buffer = new byte[1024];
        int bytesRead = stream.Read(buffer, 0, buffer.Length);
        string request = Encoding.UTF8.GetString(buffer, 0, bytesRead);
        Console.WriteLine("Received message: " + request);

        // 响应客户端
        string response = "Hello from the server!";
        byte[] responseBytes = Encoding.UTF8.GetBytes(response);
        stream.Write(responseBytes, 0, responseBytes.Length);
        Console.WriteLine("Sent response: " + response);
    }
}

这个示例中,我们首先创建一个TcpListener实例,指定监听的IP地址和端口号。然后使用Start()方法开始监听连接。在循环中,我们等待客户端连接,接受连接后调用HandleClientRequest()方法处理客户端请求。最后,关闭客户端连接并继续监听新的连接。

0
看了该问题的人还看了