sipsorcery-org / sipsorcery

A WebRTC, SIP and VoIP library for C# and .NET. Designed for real-time communications apps.
https://sipsorcery-org.github.io/sipsorcery
Other
1.38k stars 423 forks source link

Unhandled exception at WebSocketSharp.WebSocket.Send(String data) if websocket client connect and immediately close it #1120

Open programatix opened 1 month ago

programatix commented 1 month ago

Hi,

I'm testing the SIPToWebRTCBridge example project. I have updated it net8.0 with SIPSorcery version 6.2.4 and SIPSorcery.WebSocketSharp version 0.0.1.

Using webrtcsip.html, if I click Start button and immediately click the Close button to close the websocket, before it complete establishing the connection, I get an unhandled exception.

System.InvalidOperationException
  HResult=0x80131509
  Message=The current state of the connection is not Open.
  Source=websocket-sharp
  StackTrace:
   at WebSocketSharp.WebSocket.Send(String data) in WebSocketSharp\WebSocket.cs:line 2373
   at SIPSorcery.Net.WebRTCWebSocketPeer.<OnOpen>d__19.MoveNext()
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_1(Object state)
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()

I tried tracing back the call and it should be initiated from the open() function in websocket-sharp.dll which is encapsulated by a try...catch routine, but somehow it crashed the main app.

Steps to reproduce:

  1. Run the updated SIPToWebRtcBridge.
  2. Open webrtcsip.html.
  3. Click Start button.
  4. Click Allow on permission prompt.
  5. Immediately clock Close button before the connection established.
  6. Exception Unhandled will occur.

image image

programatix commented 1 month ago

It seems that the issue is caused by OnOpen() function in WebRTCWebSocketPeer class. It's an async which runs on a thread but doesn't return any Task, so exception raised inside it could not be handled by the original Try..Catch in WebSocket open(), thus making it an unhandled exception.

The easiest way out is to catch the exception in OnOpen() function for WebRTCWebSocketPeer class and log the error there. Any suggestion?