C#编程实现TCP Server服务端,监听到连接请求建立一个持续连接,实现数据通讯功能
时间: 2024-10-08 11:13:20 浏览: 26
基于C#实现的tcp服务端监听程序
在C#中,你可以使用`TcpListener`和`Socket`类创建一个基本的TCP服务器,该服务器会持续监听客户端的连接请求,一旦有连接,就保持一个持久的连接并支持双向数据传输。以下是一个简单的例子:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
class PersistentTcpServer
{
private TcpListener server;
private readonly byte[] receiveBuffer = new byte[1024];
public PersistentTcpServer(int port)
{
server = new TcpListener(IPAddress.Any, port);
server.Start();
}
public void Run()
{
Console.WriteLine($"Server started on port {server.LocalEndpoint.Port}");
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket client = server.AcceptSocket();
Console.WriteLine($"Connected to: {client.Client.RemoteEndPoint}");
// 开始一个新的线程处理每个客户端连接
Thread clientThread = new Thread(HandleClientConnectionAsync);
clientThread.Start(client);
}
}
private async void HandleClientConnectionAsync(object obj)
{
Socket client = (Socket)obj;
NetworkStream stream = client.GetStream();
while (true)
{
try
{
int bytesReceived = await stream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length);
if (bytesReceived > 0)
{
string receivedData = Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived);
Console.WriteLine($"Received: {receivedData}");
// 发送确认信息
byte[] response = Encoding.ASCII.GetBytes("Message received");
await stream.WriteAsync(response, 0, response.Length);
}
else
{
// 客户端断开连接,退出循环
break;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error handling client: {ex.Message}");
break;
}
}
stream.Close();
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
public class Program
{
public static void Main(string[] args)
{
var server = new PersistentTcpServer(12345);
server.Run();
}
}
```
在这个示例中,`Run`方法启动服务器并等待连接。每次有新连接时,它会在新的线程中调用`HandleClientConnectionAsync`方法来处理数据收发。`HandleClientConnectionAsync`中,我们通过异步的方式持续从客户端接收数据,然后发送确认信息,直到客户端主动断开连接。
阅读全文