c# - Abnormal closure of WebSocket does not return ReceiveAsync -


i have thread on server processing data received client on websocket connection:

    public httpresponsemessage get()     {         if (httpcontext.current.iswebsocketrequest)         {             httpcontext.current.acceptwebsocketrequest(processwebsocket);         }          return new httpresponsemessage(httpstatuscode.switchingprotocols);     }      private async task processwebsocket(aspnetwebsocketcontext context)     {         websocket websocket = context.websocket;    //gets current websocket object.          const int maxmessagesize = 1024;         byte[] receiveddatabuffer = new byte[maxmessagesize];         logger.debug("wsc-new websocket connection");         while (websocket.state == websocketstate.open)         {             var timeout = new cancellationtokensource(70000).token;             websocketreceiveresult websocketreceiveresult = await websocket.receiveasync(new arraysegment<byte>(receiveddatabuffer), timeout);             //if input frame cancelation frame, send close command.              if (websocketreceiveresult.messagetype == websocketmessagetype.close)             {                 await websocket.closeasync(websocketclosestatus.normalclosure, string.empty, cancellationtoken.none);                 logger.debug("wsc-close websocket connection frame received");             }             else             {                 //process received data....             }         }         logger.debug("wsc-websocket closed, websocket state: {0}", websocket.state.tostring());     } 

as long other side closes websocket connection correctly logger message @ end says websocket closed, means thread terminated correctly. if client goes sleep or program stops abruptly normal websocket closure not occur. in case websocket.receiveasync never returns. worried might have serious memory leak if enough of these threads started never terminated. timeout cancellation token supposed make return after 70 seconds not happen. if try access websocket object thread in situation following exception: cannot access disposed object.

how can await websocket.receiveasync(new arraysegment(receiveddatabuffer), timeout); close thread properly?

the problem:

closure of connection abruptly cause other socket never anymore data , leads socket being left open said.

the solution:

try using keep-alive decide when connection times out, , solution use separate thread killed drop it, not sure how work you.

starting socket ex:

thread x = new thread(() => {     connect(); }); x.start(); 

ending socket ex:

x.abort(); // force garbage collection using gc.collect(); 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -