在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
類連接到服務器,并發送一條消息。服務器接收到消息后,回復一條確認消息。
要運行此示例,請分別編譯并運行服務器和客戶端項目。你可以根據需要修改服務器和客戶端的代碼,以滿足你的需求。