温馨提示×

C# TCP/IP多线程如何实现

c#
小樊
81
2024-09-14 23:32:29
栏目: 编程语言

在C#中,使用TCP/IP和多线程可以实现高性能的网络通信。以下是一个简单的示例,展示了如何创建一个TCP服务器和客户端,并使用多线程处理并发连接。

首先,我们需要创建一个TCP服务器:

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();
        }
    }
}

接下来,我们创建一个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();
        }
    }
}

在这个示例中,服务器使用TcpListener类监听指定端口上的连接请求。当接收到新的连接请求时,服务器会创建一个新的线程来处理客户端的请求。客户端使用TcpClient类连接到服务器,并发送一条消息。服务器接收到消息后,回复一条确认消息。

要运行此示例,请分别编译并运行服务器和客户端项目。你可以根据需要修改服务器和客户端的代码,以满足你的需求。

0