阅读量:0
在C#中,实现TCP/IP服务器端可以使用System.Net.Sockets
命名空间中的TcpListener
和TcpClient
类
- 引入必要的命名空间:
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading;
- 创建一个TCP服务器类:
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(); } } }
- 在主程序中使用TCP服务器类:
class Program { static void Main(string[] args) { TcpServer server = new TcpServer(8080); server.Start(); Console.WriteLine("按任意键停止服务器..."); Console.ReadKey(); server.Stop(); } }
这个示例展示了如何使用C#创建一个简单的TCP/IP服务器端。服务器监听指定端口(在本例中为8080),并在接收到客户端连接时创建一个新线程来处理客户端请求。处理客户端请求时,服务器读取客户端发送的数据,然后向客户端发送一条响应消息。要停止服务器,只需按下任意键即可。