Setting a timeout on the server if the server in 120 did not take any of the information to the client will jump out of the loop, stop listening, close the socket
I do the test, the client direct closing process, the server did not detect disconnect, should be at the end of the 120 seconds task, but do not know why always don't perform,
CancellationTokenSource doesn't work, my environment is vs2017 system server2012
Which made it a great god, help the younger brother to give directions
Cycle to monitor
While (socket. State==WebSocketState. Open)
{
CancellationTokenSource source=new CancellationTokenSource (120 * 1000);//120 seconds timeout
ArraySegment
WebSocketReceiveResult result=await socket. ReceiveAsync (buffer, source. Token);
If (source. IsCancellationRequested)
{
WriteLog (" WebSocket to monitor overtime 120 seconds ");
Await the socket. CloseAsync (WebSocketCloseStatus NormalClosure,
String. The Empty, CancellationToken. None);
Source. The Dispose ();
break;//get news is shut down, jump out of the loop
}
Source. The Dispose ();
If (result. MessageType==WebSocketMessageType. Close)
{
WriteLog (" WebSocket receives the message off ");
Await the socket. CloseAsync (WebSocketCloseStatus NormalClosure,
String. The Empty, CancellationToken. None);
break;//get news is shut down, jump out of the loop
}
# region message processing (character interception, message forwarding)
,,,,,,,
,,,,,,,
# endregion
}
CodePudding user response:
You debug tracking is your Socket is not closed, so we can't get into that breakpoint where you close a Socket,CodePudding user response:
What programming ideas, and circulation now?Only a beginner will think that the main process is a major cycle, normal procedures now, is to let you register a delegate, websocket service framework, for example, will usually let you write a similar
server OnMessage (socket=& gt; {... });this type of code,
Server. The OnOpen (socket=& gt; {... });
Server. one rror (socket=& gt; {... });
CodePudding user response:
Well, use the async/await, so await itself is a callback, execution to await socket. ReceiveAsync (buffer, source. Token) here when the process is over, and then after a while will let () in a thread pool thread await left behind and the implementation code, usually timeout you judge and closing the socket connection object code should be treated in other threads, rather than behind await to deal with,CodePudding user response: