溫馨提示×

C#實(shí)現(xiàn)TCP/IP服務(wù)器端技巧

c#
小樊
148
2024-09-14 23:33:25
欄目: 云計算

在C#中,實(shí)現(xiàn)TCP/IP服務(wù)器端可以使用System.Net.Sockets命名空間中的TcpListenerTcpClient

  1. 引入必要的命名空間:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
  1. 創(chuàng)建一個TCP服務(wù)器類:
public class TcpServer
{
    private TcpListener _listener;
    private bool _isRunning;

    public TcpServer(int port)
    {
        _listener = new TcpListener(IPAddress.Any, port);
    }

    public void Start()
    {
        _isRunning = true;
        _listener.Start();
        Console.WriteLine("服務(wù)器已啟動,正在監(jiān)聽客戶端連接...");

        while (_isRunning)
        {
            // 當(dāng)有客戶端連接時,AcceptTcpClient會返回一個新的TcpClient實(shí)例
            TcpClient client = _listener.AcceptTcpClient();
            Console.WriteLine("客戶端已連接:{0}", client.Client.RemoteEndPoint);

            // 處理客戶端請求
            Thread clientThread = new Thread(HandleClient);
            clientThread.Start(client);
        }
    }

    public void Stop()
    {
        _isRunning = false;
        _listener.Stop();
        Console.WriteLine("服務(wù)器已停止。");
    }

    private void HandleClient(object obj)
    {
        TcpClient client = (TcpClient)obj;
        NetworkStream stream = client.GetStream();

        try
        {
            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine("收到來自客戶端的數(shù)據(jù):{0}", receivedData);

                // 處理客戶端發(fā)送的數(shù)據(jù)
                string response = "你好,我已經(jīng)收到了你的消息:" + receivedData;
                byte[] responseData = Encoding.UTF8.GetBytes(response);
                stream.Write(responseData, 0, responseData.Length);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("處理客戶端請求時出錯:{0}", ex.Message);
        }
        finally
        {
            stream.Close();
            client.Close();
        }
    }
}
  1. 在主程序中使用TCP服務(wù)器類:
class Program
{
    static void Main(string[] args)
    {
        TcpServer server = new TcpServer(8080);
        server.Start();

        Console.WriteLine("按任意鍵停止服務(wù)器...");
        Console.ReadKey();

        server.Stop();
    }
}

這個示例展示了如何使用C#創(chuàng)建一個簡單的TCP/IP服務(wù)器端。服務(wù)器監(jiān)聽指定端口(在本例中為8080),并在接收到客戶端連接時創(chuàng)建一個新線程來處理客戶端請求。處理客戶端請求時,服務(wù)器讀取客戶端發(fā)送的數(shù)據(jù),然后向客戶端發(fā)送一條響應(yīng)消息。要停止服務(wù)器,只需按下任意鍵即可。

0