溫馨提示×

c# tcplistener如何創(chuàng)建

c#
小樊
81
2024-11-20 03:19:06
欄目: 編程語言

在C#中,您可以使用TcpListener類創(chuàng)建一個(gè)TCP監(jiān)聽器

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

class TcpListenerExample
{
    static void Main(string[] args)
    {
        // 設(shè)置監(jiān)聽的IP地址和端口號(hào)
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        int port = 8080;

        // 創(chuàng)建一個(gè)TcpListener實(shí)例
        TcpListener listener = new TcpListener(ipAddress, port);

        // 開始監(jiān)聽連接
        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);

                // 關(guān)閉客戶端連接
                client.Close();
                Console.WriteLine("Client disconnected.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
        finally
        {
            // 停止監(jiān)聽
            listener.Stop();
            Console.WriteLine("TCP Listener stopped.");
        }
    }

    static void HandleClientRequest(TcpClient client)
    {
        // 讀取客戶端發(fā)送的數(shù)據(jù)
        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);

        // 響應(yīng)客戶端
        string response = "Hello from the server!";
        byte[] responseBytes = Encoding.UTF8.GetBytes(response);
        stream.Write(responseBytes, 0, responseBytes.Length);
        Console.WriteLine("Sent response: " + response);
    }
}

這個(gè)示例中,我們首先創(chuàng)建一個(gè)TcpListener實(shí)例,指定監(jiān)聽的IP地址和端口號(hào)。然后使用Start()方法開始監(jiān)聽連接。在循環(huán)中,我們等待客戶端連接,接受連接后調(diào)用HandleClientRequest()方法處理客戶端請求。最后,關(guān)閉客戶端連接并繼續(xù)監(jiān)聽新的連接。

0