public async Task Receive()
        {
            lock (SyncObj)
            {
                //Websocket only allows one receive call at a time.
                if (isReading)
                {
                    return;
                }

                isReading = true;
            }

            try
            {
                WebSocketReceiveResult result = await m_Socket.ReceiveAsync(new ArraySegment <byte>(InternalBuffer), CancellationToken.None);

                if (result == null)
                {
                    return;
                }

                if (result.MessageType == WebSocketMessageType.Binary)
                {
                    lock (SyncObj)
                    {
                        OnMessage?.Invoke(new ArraySegment <byte>(InternalBuffer, 0, result.Count));
                    }
                }
                else if (result.MessageType == WebSocketMessageType.Close)
                {
                    await Close();

                    OnClose?.Invoke(WebSocketHelpers.ParseCloseCodeEnum((int)result.CloseStatus));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"{nameof(DefaultWebSocketClient)} failed to receive message. Reason: {e}");
                throw;
            }
            finally
            {
                isReading = false;
            }
        }
Esempio n. 2
0
 /// <summary>
 /// Delegate onClose event from JSLIB to native sharp event
 /// Is called by WebSocketFactory
 /// </summary>
 /// <param name="closeCode">Close status code.</param>
 public void DelegateOnCloseEvent(int closeCode)
 {
     this.OnClose?.Invoke(WebSocketHelpers.ParseCloseCodeEnum(closeCode));
 }