溫馨提示×

c# tcplistener有何創(chuàng)建法

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

在C#中,TcpListener類用于創(chuàng)建一個TCP服務(wù)器,監(jiān)聽來自客戶端的連接請求

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

class TcpServer
{
    static void Main(string[] args)
    {
        // 設(shè)置監(jiān)聽的IP地址和端口號
        IPAddress ipAddress = IPAddress.Any;
        int port = 12345;

        // 創(chuàng)建一個TcpListener實例
        TcpListener tcpListener = new TcpListener(ipAddress, port);

        // 開始監(jiān)聽客戶端連接請求
        Console.WriteLine("Server is listening...");
        tcpListener.Start();

        while (true)
        {
            // 等待客戶端連接請求
            Console.Write("Waiting for a client connection...");
            TcpClient client = await tcpListener.AcceptTcpClientAsync();

            // 處理客戶端連接
            HandleClientConnection(client);
        }
    }

    static async Task HandleClientConnection(TcpClient client)
    {
        // 獲取客戶端的輸入流和輸出流
        NetworkStream inputStream = client.GetStream();
        NetworkStream outputStream = client.GetStream();

        // 讀取客戶端發(fā)送的數(shù)據(jù)
        byte[] buffer = new byte[1024];
        int bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length);
        string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
        Console.WriteLine($"Received from client: {receivedData}");

        // 向客戶端發(fā)送響應(yīng)數(shù)據(jù)
        string responseData = "Hello from server!";
        byte[] responseBytes = Encoding.UTF8.GetBytes(responseData);
        await outputStream.WriteAsync(responseBytes, 0, responseBytes.Length);
        Console.WriteLine("Sent to client: " + responseData);

        // 關(guān)閉客戶端連接
        client.Close();
    }
}

在這個示例中,我們首先創(chuàng)建了一個TcpListener實例,指定監(jiān)聽的IP地址(IPAddress.Any表示監(jiān)聽所有可用的網(wǎng)絡(luò)接口)和端口號(12345)。然后,我們使用Start()方法開始監(jiān)聽客戶端連接請求。

while循環(huán)中,我們使用AcceptTcpClientAsync()方法等待客戶端連接請求。當(dāng)接收到客戶端連接時,我們調(diào)用HandleClientConnection()方法處理客戶端連接。在這個方法中,我們從客戶端讀取數(shù)據(jù),向客戶端發(fā)送響應(yīng)數(shù)據(jù),然后關(guān)閉客戶端連接。

0