C#TcpListener 实现socket服务端,只能有一个客户端连接,发送消息区分发送的还是接收的,按照一个字段区分发送的消息体,30秒超时时间,消息有结尾符$$$,代码性能一定要非常高
时间: 2024-09-26 21:09:20 浏览: 33
C#实现Tcp通信服务端、客户端数据的发送与接收,发送到指定终端、群发
在C#中,你可以使用`TcpListener`类来创建一个简单的TCP服务器,它允许单个客户端连接并处理消息。这里是一个示例,展示了如何实现一个高性能的、具备30秒超时限制以及特殊结尾符($$$)的socket服务端:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SimpleServer
{
private TcpListener _listener;
private byte[] _endOfMessageMarker = new byte[] { (byte)'$', (byte)'$', (byte)'$' };
private readonly TimeSpan _timeout = TimeSpan.FromSeconds(30);
public void StartListening(IPEndPoint endpoint)
{
_listener = new TcpListener(endpoint);
_listener.Start();
Console.WriteLine("Socket server started on " + endpoint.Address.ToString() + ":" + endpoint.Port);
while (true)
{
try
{
var client = await _listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
Task.Run(() => HandleConnection(client, reader, writer));
}
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred: {ex.Message}");
}
}
}
private async void HandleConnection(TcpClient client, StreamReader reader, StreamWriter writer)
{
try
{
byte[] buffer = new byte[4096];
int bytesRead;
// Read until the end of message marker or timeout
while ((bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0 && Array.IndexOf(buffer, _endOfMessageMarker) == -1)
{
if (!_listener.Server.IsBound || !_listener.Server.IsListening)
{
break; // Server has stopped listening
}
if (_timeoutelapsed >= _timeout)
{
writer.WriteLine("Connection timed out.");
return;
}
// Write received bytes to console for sending back
Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead));
// Send data back to client
await writer.WriteAsync(buffer, 0, bytesRead);
}
if (Array.IndexOf(buffer, _endOfMessageMarker) != -1)
{
// Message received with correct marker
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead - _endOfMessageMarker.Length);
Console.WriteLine("Received message: " + message);
writer.WriteLine("Message processed");
}
else
{
Console.WriteLine("Invalid message format. No end of message marker found.");
}
// Gracefully close the connection after processing the message
writer.Flush();
client.Close();
}
catch (Exception ex)
{
Console.WriteLine($"Error handling client: {ex.Message}");
}
}
}
// To start the server:
var endpoint = new IPEndPoint(IPAddress.Any, 12345); // Replace with your desired port
var server = new SimpleServer();
server.StartListening(endpoint);
```
这个代码实现了以下功能:
1. 只接受一个客户端连接。
2. 区分发送和接收的数据,并根据结束符$$判断消息是否完整。
3. 设置30秒超时时间。
4. 高效地读取和写入数据。
阅读全文