Exemplo n.º 1
0
        /// <summary>
        /// Parses the result of data read from the websocket.
        /// </summary>
        /// <param name="Result">The WebSocketReceiveResult.</param>
        /// <param name="ReadBuffer">The byte array buffer read from the socket stream.</param>
        private async Task ParseMessage(WebSocketReceiveResult Result, byte[] ReadBuffer)
        {
            if (!Result.EndOfMessage)
            {
                return;
            }
            RequestHistory.Add(DateTime.Now);
            while (RequestHistory.Count > 50)
            {
                RequestHistory.RemoveAt(0);
            }
            if (RequestHistory.Where(time => DateTime.Now - time < TimeSpan.FromSeconds(1)).Count() > 40)
            {
                await Player.WarnOrBan(this);
            }
            if (Result.MessageType == WebSocketMessageType.Text)
            {
                var trimmedString = Encoding.UTF8.GetString(TrimBytes(ReadBuffer));
                var jsonMessage   = JSON.Decode(trimmedString);

                StringMessageReceived?.Invoke(this, jsonMessage);
            }
            else if (Result.MessageType == WebSocketMessageType.Binary)
            {
                BinaryMessageReceived?.Invoke(this, TrimBytes(ReadBuffer));
            }
            else if (Result.MessageType == WebSocketMessageType.Close)
            {
                SocketClosed?.Invoke(this, EventArgs.Empty);
            }
        }
Exemplo n.º 2
0
 private void SetupEvents()
 {
     Socket.OnMessage((s, e) =>
     {
         SocketMessageEventArgs args = new SocketMessageEventArgs
         {
             Message = s
         };
         MessageReceived?.Invoke(this, args);
     });
     Socket.OnConnect((s) =>
     {
         SocketOpened?.Invoke(this, null);
     });
     Socket.OnDisconnect((status, reason, socket) =>
     {
         SocketClosedEventArgs args = new SocketClosedEventArgs
         {
             Reason   = reason,
             WasClean = false,
             Code     = status
         };
         Console.WriteLine(status);
         SocketClosed?.Invoke(this, args);
     });
 }
Exemplo n.º 3
0
        /// <summary>
        /// 关闭Socket
        /// </summary>
        /// <returns></returns>
        public void CloseSocket()
        {
            lock (this)
            {
                if (_connSuccess == false)
                {
                    return;
                }

                try
                {
                    if (_sokClient != null)
                    {
                        _sokClient.Shutdown(SocketShutdown.Both);
                        _sokClient.Dispose();
                        _sokClient.Close();
                        _sokClient = null;
                    }
                }
                catch
                {
                    _sokClient = null;
                }

                _connSuccess = false;
                SocketClosed?.Invoke();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Continuously reads data from the websocket.
        /// </summary>
        public async Task HandleSocket()
        {
            try
            {
                var buffer = new byte[Utilities.Server.ReceiveBufferSize];
                WebSocketReceiveResult result = await ClientSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
                await ParseMessage(result, buffer);

                while (!ClientSocket.CloseStatus.HasValue)
                {
                    buffer = new byte[Utilities.Server.ReceiveBufferSize];
                    result = await ClientSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
                    await ParseMessage(result, buffer);
                }
                if (Utilities.Server.ClientList.Contains(this))
                {
                    Utilities.Server.ClientList.Remove(this);
                }
                await ClientSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
            }
            catch (Exception ex)
            {
                if (Utilities.Server.ClientList.Contains(this))
                {
                    Utilities.Server.ClientList.Remove(this);
                }
                await ClientSocket.CloseOutputAsync(WebSocketCloseStatus.InternalServerError, "An unhandled exception occurred.", CancellationToken.None);

                SocketError?.Invoke(this, ex);
                SocketClosed?.Invoke(this, EventArgs.Empty);
                ClientSocket.Dispose();
            }
        }
Exemplo n.º 5
0
        private void WebSocket_OnClose(object sender, CloseEventArgs e)
        {
            IsOpen = false;
            IsStrangerConnected = false;

            var eventArgs = new SocketClosedEventArgs(e.WasClean, e.Code, e.Reason);

            SocketClosed?.Invoke(this, eventArgs);
        }
        /// <summary>
        /// Raises the SocketClosed event.
        /// </summary>
        protected void InvokeSocketClosed()
        {
            var prevSocketOpenedEventCount = Interlocked.CompareExchange(ref _socketOpenedEventCount, 0, 1);

            if (prevSocketOpenedEventCount == 1)
            {
                SocketClosed?.Invoke(this, EventArgs.Empty);
            }
        }
Exemplo n.º 7
0
        private async Task Connect()
        {
            if (_conn != null)
            {
                await _conn.DisposeAsync();
            }

            _currentHeartbeatInterval = null;

            _conn = new ShardConnection(_uri, _logger, _jsonSerializerOptions)
            {
                OnReceive = OnReceive,
                OnOpen    = () => SocketOpened?.Invoke(),
                OnClose   = (closeStatus, message) => SocketClosed?.Invoke(closeStatus, message)
            };
        }
Exemplo n.º 8
0
        private void CallOnDisconnected(string messageOverride)
        {
            try
            {
                _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
            }
            catch { }

            SocketClosedEventArgs args = new SocketClosedEventArgs
            {
                Reason   = messageOverride != null ? messageOverride : _ws.CloseStatusDescription,
                WasClean = false,
                Code     = _ws.CloseStatus != null ? (int)_ws.CloseStatus.Value : -1
            };

            SocketClosed?.Invoke(this, args);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Hooks up events to automatically be redirected to the interface's events.
        /// </summary>
        private void HookupEvents()
        {
            Socket.OnMessage += (sender, e) =>
            {
                SocketMessageEventArgs args = new SocketMessageEventArgs
                {
                    Message = e.Data
                };
                MessageReceived?.Invoke(this, args);
            };

            Socket.OnError += (sender, e) =>
            {
                SocketErrorEventArgs args = new SocketErrorEventArgs
                {
                    Exception = e.Exception,
                    Message   = e.Message
                };
                SocketError?.Invoke(this, args);
            };

            Socket.OnClose += (sender, e) =>
            {
                SocketClosedEventArgs args = new SocketClosedEventArgs
                {
                    Code     = e.Code,
                    Reason   = e.Reason,
                    WasClean = e.WasClean
                };
                SocketClosed?.Invoke(this, args);
            };

            Socket.OnOpen += (sender, e) =>
            {
                SocketOpened?.Invoke(this, null);
            };
        }
 /// <summary>
 /// Handles <see cref="IWebSocket.Closed"/> event.
 /// </summary>
 protected virtual void OnClosed() => SocketClosed?.Invoke();
Exemplo n.º 11
0
 private void WebSocket_OnClose(object sender, CloseEventArgs e)
 {
     SocketClosed?.Invoke(sender,
                          new WebSocketCloseEventArgs(e.Code, e.Reason, e.WasClean));
 }
Exemplo n.º 12
0
 private void Socket_Closed(object sender, EventArgs e)
 {
     SocketClosed?.Invoke(sender, e);
 }
Exemplo n.º 13
0
 private void WebSocket_Closed(object sender, EventArgs e)
 {
     SetUpDisconnectedState();
     SocketClosed?.Invoke(this, EventArgs.Empty);
 }
Exemplo n.º 14
0
 protected override void OnClose(CloseEventArgs e)
 {
     Debug.Log("OnCloneEvent");
     base.OnClose(e);
     SocketClosed?.Invoke();
 }
Exemplo n.º 15
0
 /// <summary>
 /// Handles <see cref="IWebSocket.Closed"/> event.
 /// </summary>
 protected virtual void OnClosed(object sender, WebSocketCloseData e) => SocketClosed?.Invoke();
Exemplo n.º 16
0
 protected virtual void OnSocketClosed()
 {
     SocketClosed?.Invoke(this);
 }
Exemplo n.º 17
0
 public void OnSocketClosed()
 {
     SocketClosed?.Invoke(this, EventArgs.Empty);
 }