C# TCP/IP多線程如何實(shí)現(xiàn)

c#
小樊
81
2024-09-14 23:32:29
欄目: 編程語言

在C#中,使用TCP/IP和多線程可以實(shí)現(xiàn)高性能的網(wǎng)絡(luò)通信。以下是一個(gè)簡單的示例,展示了如何創(chuàng)建一個(gè)TCP服務(wù)器和客戶端,并使用多線程處理并發(fā)連接。

首先,我們需要?jiǎng)?chuàng)建一個(gè)TCP服務(wù)器:

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

namespace TcpServer
{
    class Program
    {
        private static TcpListener _listener;

        static void Main(string[] args)
        {
            _listener = new TcpListener(IPAddress.Any, 8080);
            _listener.Start();

            Console.WriteLine("Server is listening on port 8080...");

            while (true)
            {
                TcpClient client = _listener.AcceptTcpClient();
                Thread thread = new Thread(HandleClient);
                thread.Start(client);
            }
        }

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

            byte[] buffer = new byte[1024];
            int bytesRead = stream.Read(buffer, 0, buffer.Length);

            string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine($"Received message: {message}");

            string response = "Message received";
            byte[] responseData = Encoding.ASCII.GetBytes(response);
            stream.Write(responseData, 0, responseData.Length);

            stream.Close();
            client.Close();
        }
    }
}

接下來,我們創(chuàng)建一個(gè)TCP客戶端:

using System;
using System.Net.Sockets;
using System.Text;

namespace TcpClient
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient("localhost", 8080);
            NetworkStream stream = client.GetStream();

            string message = "Hello, server!";
            byte[] data = Encoding.ASCII.GetBytes(message);
            stream.Write(data, 0, data.Length);

            byte[] buffer = new byte[1024];
            int bytesRead = stream.Read(buffer, 0, buffer.Length);

            string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine($"Server response: {response}");

            stream.Close();
            client.Close();
        }
    }
}

在這個(gè)示例中,服務(wù)器使用TcpListener類監(jiān)聽指定端口上的連接請(qǐng)求。當(dāng)接收到新的連接請(qǐng)求時(shí),服務(wù)器會(huì)創(chuàng)建一個(gè)新的線程來處理客戶端的請(qǐng)求。客戶端使用TcpClient類連接到服務(wù)器,并發(fā)送一條消息。服務(wù)器接收到消息后,回復(fù)一條確認(rèn)消息。

要運(yùn)行此示例,請(qǐng)分別編譯并運(yùn)行服務(wù)器和客戶端項(xiàng)目。你可以根據(jù)需要修改服務(wù)器和客戶端的代碼,以滿足你的需求。

0