c#tcp通信服务器端AsyncTcpServer
时间: 2023-11-21 14:40:57 浏览: 50
你可以使用C#中的异步编程模型来创建一个通信服务器端。下面是一个示例代码,演示了如何使用AsyncTcpServer类来实现:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class AsyncTcpServer
{
private TcpListener listener;
public AsyncTcpServer(IPAddress ipAddress, int port)
{
listener = new TcpListener(ipAddress, port);
}
public async Task Start()
{
listener.Start();
Console.WriteLine("Server started. Listening for incoming connections...");
while (true)
{
TcpClient client = await listener.AcceptTcpClientAsync();
HandleClient(client);
}
}
private async void HandleClient(TcpClient client)
{
Console.WriteLine($"Client connected: {client.Client.RemoteEndPoint}");
try
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
string requestData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received data from client: {requestData}");
// 处理接收到的数据并返回响应
string responseData = $"Server received: {requestData}";
byte[] responseBytes = Encoding.ASCII.GetBytes(responseData);
await stream.WriteAsync(responseBytes, 0, responseBytes.Length);
Console.WriteLine($"Sent response to client: {responseData}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred: {ex.Message}");
}
finally
{
client.Close();
Console.WriteLine($"Client disconnected: {client.Client.RemoteEndPoint}");
}
}
}
class Program
{
static async Task Main(string[] args)
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 8080;
AsyncTcpServer server = new AsyncTcpServer(ipAddress, port);
await server.Start();
}
}
```
你可以根据需要修改IP地址和端口号。这个示例创建了一个异步的TCP服务器,接受客户端连接并处理接收到的数据。它使用ASCII编码来传输文本数据,你可以根据需要进行修改。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cs](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)