写一个c# 多线程处理客户端请求的案例
时间: 2024-02-16 15:05:07 浏览: 69
以下是一个简单的 C# 多线程处理客户端请求的案例,使用了 TCP/IP 协议进行客户端和服务器之间的通信:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class Server
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(IPAddress.Any, 8888);
serverSocket.Start();
Console.WriteLine("Server started");
while (true)
{
TcpClient client = serverSocket.AcceptTcpClient();
Console.WriteLine("Client connected");
Thread thread = new Thread(new ParameterizedThreadStart(HandleClient));
thread.Start(client);
}
}
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 = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received message: {0}", message);
// Handle client request here...
byte[] response = System.Text.Encoding.ASCII.GetBytes("Server response");
stream.Write(response, 0, response.Length);
client.Close();
}
}
```
该服务器在端口 8888 上监听客户端连接,并在接收到连接请求时启动一个新的线程来处理客户端请求。在 `HandleClient` 方法中,服务器接收客户端发送的消息,处理请求并发送响应消息。注意到该方法接受一个 `object` 参数,因为线程启动时只能传递一个对象,因此需要将 `TcpClient` 对象作为参数进行传递。
阅读全文