Code-Sharp/WampSharp

Connection Error Issues

oollie34 opened this issue · 1 comments

Describe the bug
Having a couple of issues with connection errors and not too sure how to resolve them, I'm seeing stack traces appear in my log file originating from WamSharp, throwing a connection error even though it should be a disconnect event as it is a broken pipe.

2023-08-23 07:47:35.8562 ERROR .NET ThreadPool Worker 3 A connection error occurredSystem.IO.IOException: Unable to write data to the transport connection: Broken pipe.
 ---> System.Net.Sockets.SocketException (32): Broken pipe
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.CreateException(SocketError error, Boolean forAsyncThrow)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.SendAsyncForNetworkStream(Socket socket, CancellationToken cancellationToken)
   at System.Net.Sockets.NetworkStream.WriteAsync(ReadOnlyMemory`1 buffer, CancellationToken cancellationToken)
   at System.Net.Security.SslStream.WriteSingleChunk[TIOAdapter](ReadOnlyMemory`1 buffer, CancellationToken cancellationToken)
   at System.Net.Security.SslStream.WriteAsyncInternal[TIOAdapter](ReadOnlyMemory`1 buffer, CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
   at System.Net.Security.SslStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at SuperSocket.ClientEngine.AuthenticatedStreamTcpSession.SendInternalAsync(PosList`1 items)
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
   at SuperSocket.ClientEngine.AuthenticatedStreamTcpSession.SendInternalAsync(PosList`1 items)
   at SuperSocket.ClientEngine.TcpClientSession.TrySend(ArraySegment`1 segment)
   at SuperSocket.ClientEngine.ClientSession.Send(ArraySegment`1 segment)
   at WebSocket4Net.WebSocket.OnPingTimerCallback(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.TimerQueueTimer.Fire(Boolean isThreadPool)
   at System.Threading.TimerQueue.FireNextTimers()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
--- End of stack trace from previous location ---

   --- End of inner exception stack trace ---
   at System.Net.Security.SslStream.<WriteSingleChunk>g__CompleteWriteAsync|153_1[TIOAdapter](ValueTask writeTask, Byte[] bufferToReturn)
   at System.Net.Security.SslStream.WriteAsyncInternal[TIOAdapter](ReadOnlyMemory`1 buffer, CancellationToken cancellationToken)
   at SuperSocket.ClientEngine.AuthenticatedStreamTcpSession.SendInternalAsync(PosList`1 items) | WampSharp.Logging.LogErrorExtensions.Error
2023-08-23 07:47:35.8562 ERROR .NET ThreadPool Worker 3 A WebSocket connection error has occurred | WebSocket4Net.WebSocket.client_Error
2023-08-23 07:47:35.8574 ERROR .NET ThreadPool Worker 3 Recieved error event from subscriber Unable to write data to the transport connection: Broken pipe. | System.Reactive.Sink`1.ForwardOnError

I'm firstly not sure why I'm seeing the whole stack trace getting written to my log file? I'm seeing this numerous times a day where it just disconnects with no reason provided, the server is still running fine.

To Reproduce
My connection code is as follows, maybe I am doing something wrong here?

private async Task<bool> ThreadSafeConnect(string address, bool untrustedSsl, bool rawJsonLogging, int pingInterval)
{
    Address = address;
    RawJsonLogging = rawJsonLogging;
    AllowUntrustedSsl = untrustedSsl;
    ActiveSockets.TryAdd(Address, this);
    _pingInterval = pingInterval;
    if (!(Interlocked.CompareExchange(ref _openCalls, 1, 0) == 1))
    {
        _logger.Info("connecting to a WebSocket at " + Address);
        WampChannelFactory factory = new();
        if (AllowUntrustedSsl)
        {
            _channel = factory
                .ConnectToRealm("default")
                .WebSocket4NetTransport(s => CreateWebSocket(s, Address))
                .SetSecurityOptions(GetSecurity())
                .JsonSerialization()
                .Build();
        }
        else
        {
            _channel = factory
                .ConnectToRealm("default")
                .WebSocket4NetTransport(s => CreateWebSocket(s, Address))
                .JsonSerialization()
                .Build();
        }
        _channel.RealmProxy.Monitor.ConnectionError += Monitor_ConnectionError;
        if (await OpenSocket())
        {
            _channel.RealmProxy.Monitor.ConnectionBroken += Monitor_ConnectionBroken;
            _hasConnected = true;
            return true;
        }
        else
        {
            _openCalls = 0;
            return false;
        }
    }
    return false;
}
private WebSocket CreateWebSocket(string subprotocolName, string serverAddress)
{
    WebSocket result = new(uri: serverAddress,
                                  subProtocol: subprotocolName,
                                  version: WebSocketVersion.None)
    {
        AutoSendPingInterval = _pingInterval,
        EnableAutoSendPing = true
    };
    return result;
}
private async Task<bool> OpenSocket()
{
    try
    {
        if (_channel == null || Open)
            return false;
        await _channel.Open().ConfigureAwait(false);
        _logger.Info($"Using WebSocket realm {_channel.RealmProxy.Name}");
        RealmProxy = _channel.RealmProxy;
        await Task.FromResult(0);
        return true;
    }
    catch
    {
        _logger.Error($"Unable to connect to the WebSocket at {Address}");
        _openCalls = 0;
        return false;
    }
}

Reproduction in my enviroment is just connect and wait, although I can never seem to catch this exception inside visual studio.
Thanks in advance.

Moved away from using WebSocket4Net and now I'm getting some more consistent behavior, does appear to be an exception that isn't handled somewhere though.