在C#中,使用Socket实现多线程通信可以通过创建一个服务器端和客户端并为每个连接创建单独的线程来完成。这里是一个简单的示例,展示了如何实现多线程Socket通信:
- 首先,创建一个服务器端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class Server
{
private TcpListener _listener;
public void Start(int port)
{
_listener = new TcpListener(IPAddress.Any, port);
_listener.Start();
Console.WriteLine("Server started on port: " + port);
while (true)
{
TcpClient client = _listener.AcceptTcpClient();
Thread clientThread = new Thread(HandleClient);
clientThread.Start(client);
}
}
private void HandleClient(object obj)
{
TcpClient client = (TcpClient)obj;
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[256];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string receivedData = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received data: " + receivedData);
string response = "Server received: " + receivedData;
byte[] responseData = System.Text.Encoding.ASCII.GetBytes(response);
stream.Write(responseData, 0, responseData.Length);
stream.Close();
client.Close();
}
}
- 然后,创建一个客户端:
using System;
using System.Net.Sockets;
class Client
{
public void Connect(string serverIp, int port)
{
TcpClient client = new TcpClient(serverIp, port);
NetworkStream stream = client.GetStream();
string message = "Hello, Server!";
byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
byte[] buffer = new byte[256];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string response = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Server response: " + response);
stream.Close();
client.Close();
}
}
- 最后,在主程序中启动服务器和客户端:
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Server server = new Server();
Thread serverThread = new Thread(() => server.Start(8000));
serverThread.Start();
Thread.Sleep(1000);
Client client = new Client();
client.Connect("127.0.0.1", 8000);
Console.ReadLine();
}
}
这个示例中,服务器监听指定端口上的连接请求,并为每个连接创建一个新线程。客户端连接到服务器并发送一条消息,然后接收服务器的响应。这种方法可以轻松地扩展到处理多个客户端连接。
版权声明:除特别声明外,本站所有文章皆是本站原创,转载请以超链接形式注明出处!