问题描述
我的 tcp 服务器被Close_Waits"挂起.我需要一个示例程序来处理来自客户端的持久连接.
I am having tcp server which gets hanged with "Close_Waits". I need to have an example program which deals with the persistent connection from the client.
我尝试捕获异常,然后关闭捕获内的套接字.但没有运气!
I have tried catching the exceptions and then closing the socket inside the catch. But no luck!
protected virtual void ReceiveCallBack(IAsyncResult result)
{
var wrapper = (ConnectedSocketWrapper)result.AsyncState;
try
{
int bytesRead = 0;
bytesRead = wrapper.ConnectedSocket.EndReceive(result);
LogInfo("Byte Read" + bytesRead.ToString());
if (bytesRead > 0)
{
LogInfo("inside Byte Read > 0 : " + bytesRead.ToString());
byte[] dataRead = wrapper.Buffer.Take(bytesRead).ToArray();
wrapper.ConnectedSocket.BeginReceive(wrapper.Buffer, 0, this.configuration.BytesToReceiveInReadOperation, SocketFlags.None, this.ReceiveCallBack, wrapper);
DataReceivedByServer dataReceived = new DataReceivedByServer(wrapper.Token, dataRead);
EventDispatcher.RaiseEvent(dataReceived);
if (DataReceived != null)
{
DataReceived(this, new DataReceivedEventArgs(dataRead, wrapper.Token));
}
}
else
{
EventDispatcher.RaiseEvent(new ClientDisconnected(wrapper.Token, "Read 0 bytes (client disconnected gracefully)", wrapper.ConnectedSocket.RemoteEndPoint.ToString()));
LogInfo("inside Byte Read = 0 : " + bytesRead.ToString());
Close(wrapper.ConnectedSocket);
Socket removeSocket;
connectedSockets.TryRemove(wrapper.Token, out removeSocket);
}
}
catch
{
Close(wrapper.ConnectedSocket);
throw;
}
}
我需要一个挂起的空闲 TCP 服务器来无缝处理请求.
I need to have a hung free TCP server which handles the requests seamlessly.
推荐答案
如果我是你,我会检查代码和/或使用这个 simplsockets,它的可读性很强.
If I were you I would inspect code and/or use this one simplsockets, it's quite readable.
还要检查这个MultiProtocolAspNetCore,是关于如何构建TCP
ASP.NET Core
上的服务器.
Also check this one MultiProtocolAspNetCore, it's about how to build TCP
server on top ASP.NET Core
.
另请阅读这篇很棒的TCP/IP .NET Socket FAQ.
这篇关于如何修复:客户端断开连接后,tcp 服务器关闭等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!