statianzo/Fleck

WebSocketConnetction.SendBytes([]) possible null reference when this.Socket is null

NoNotNow opened this issue · 0 comments

During send operations from different threads we frequently get null reference exceptions.

Object reference not set to an instance of an object.
   at Fleck.WebSocketConnection.CloseSocket()
   at Fleck.WebSocketConnection.<>c__DisplayClass61_0.<SendBytes>b__1(Exception e)
   at Fleck.SocketWrapper.<>c__DisplayClass29_0.<Send>b__3(Task t)
   at System.Threading.Tasks.Task.Execute()

The stack trace points to this code in WebSocketConnection:

private Task SendBytes(byte[] bytes, Action callback = null)
  {
    return this.Socket.Send(bytes, (Action) (() =>
    {
      FleckLog.Debug("Sent " + (object) bytes.Length + " bytes");
      if (callback == null)
        return;
      callback();
    }), (Action<Exception>) (e =>
    {
      if (e is IOException)
        FleckLog.Debug("Failed to send. Disconnecting.", e);
      else
        FleckLog.Info("Failed to send. Disconnecting.", e);
      this.CloseSocket();
    }));
  }

I suggest adding null checks to the CloseSocket method

   private void CloseSocket()
    {
      this._closing = true;
      this.OnClose();
      this._closed = true;
      this.Socket?.Close();
      this.Socket?.Dispose();
      this._closing = false;
    }