在C#中,實現TCP/IP服務器端可以使用System.Net.Sockets
命名空間中的TcpListener
和TcpClient
類
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class TcpServer
{
private TcpListener _listener;
private bool _isRunning;
public TcpServer(int port)
{
_listener = new TcpListener(IPAddress.Any, port);
}
public void Start()
{
_isRunning = true;
_listener.Start();
Console.WriteLine("服務器已啟動,正在監聽客戶端連接...");
while (_isRunning)
{
// 當有客戶端連接時,AcceptTcpClient會返回一個新的TcpClient實例
TcpClient client = _listener.AcceptTcpClient();
Console.WriteLine("客戶端已連接:{0}", client.Client.RemoteEndPoint);
// 處理客戶端請求
Thread clientThread = new Thread(HandleClient);
clientThread.Start(client);
}
}
public void Stop()
{
_isRunning = false;
_listener.Stop();
Console.WriteLine("服務器已停止。");
}
private void HandleClient(object obj)
{
TcpClient client = (TcpClient)obj;
NetworkStream stream = client.GetStream();
try
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("收到來自客戶端的數據:{0}", receivedData);
// 處理客戶端發送的數據
string response = "你好,我已經收到了你的消息:" + receivedData;
byte[] responseData = Encoding.UTF8.GetBytes(response);
stream.Write(responseData, 0, responseData.Length);
}
}
catch (Exception ex)
{
Console.WriteLine("處理客戶端請求時出錯:{0}", ex.Message);
}
finally
{
stream.Close();
client.Close();
}
}
}
class Program
{
static void Main(string[] args)
{
TcpServer server = new TcpServer(8080);
server.Start();
Console.WriteLine("按任意鍵停止服務器...");
Console.ReadKey();
server.Stop();
}
}
這個示例展示了如何使用C#創建一個簡單的TCP/IP服務器端。服務器監聽指定端口(在本例中為8080),并在接收到客戶端連接時創建一個新線程來處理客戶端請求。處理客戶端請求時,服務器讀取客戶端發送的數據,然后向客戶端發送一條響應消息。要停止服務器,只需按下任意鍵即可。