问题
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;
}
}
I need to have a hung free TCP server which handles the requests seamlessly.
回答1:
If I were you I would inspect code and/or use this one simplsockets, it's quite readable.
Also check this one MultiProtocolAspNetCore, it's about how to build TCP
server on top ASP.NET Core
.
Also read this awesome TCP/IP .NET Socket FAQ.
来源:https://stackoverflow.com/questions/56662099/how-to-fix-the-tcp-server-having-close-waits-after-client-disconnected