Dispose() public abstract method

public abstract Dispose ( ) : void
return void
Esempio n. 1
0
        /// <inheritdoc />
        public async Task ConnectAsync(ISession session, CancellationToken ct = default(CancellationToken),
                                       bool appearOnline = false, int connectTimeout = 5000)
        {
            if (_listener != null)
            {
                await _listener.CloseAsync();

                _messageReplies.Clear();
                _listener.Dispose();
                _listener = null;
            }

            var addr = new UriBuilder(_baseUri)
            {
                Path  = "/ws",
                Query = string.Concat("lang=en&status=", appearOnline, "&token=", session.AuthToken)
            };

            var timeoutTask = Task.Delay(TimeSpan.FromMilliseconds(connectTimeout), ct);
            var connectTask = _client.ConnectAsync(addr.Uri, ct);

            // Limit time (msec) allowed for connect attempts.
            if (await Task.WhenAny(connectTask, timeoutTask).ConfigureAwait(false) == timeoutTask)
            {
                throw new TimeoutException($"Socket connect timed out after '{connectTimeout}' milliseconds.");
            }

            _listener = await connectTask.ConfigureAwait(false);

            ReadSocketAsync(ct);
            WriteSocketAsync(ct);
        }
        private async Task HandleWebSocketAsync(WebSocket websocket)
        {
            try
            {
                if (OnConnect != null)
                    OnConnect.Invoke(websocket);

                while (websocket.IsConnected)
                {
                    var message = await websocket.ReadStringAsync(CancellationToken.None)
                                                 .ConfigureAwait(false);
                    if (message != null && OnMessage != null)
                        OnMessage.Invoke(websocket, message);
                }

                if (OnDisconnect != null)
                    OnDisconnect.Invoke(websocket);
            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError.Invoke(websocket, ex);
            }
            finally
            {
                websocket.Dispose();
            }
        }
Esempio n. 3
0
        public void Disconnect()
        {
            Log.Print(LogType.Game, "Client disconnected.");
            if (Socket.IsConnected)
            {
                Socket.Close();
            }

            isReady = false;

            Socket.Dispose();
        }
Esempio n. 4
0
        private static async Task EchoAllIncomingMessagesAsync(WebSocket webSocket, CancellationToken cancellation)
        {
            Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' connected.");
            var sw = new Stopwatch();

            try
            {
                while (webSocket.IsConnected && !cancellation.IsCancellationRequested)
                {
                    try
                    {
                        var messageText = await webSocket.ReadStringAsync(cancellation).ConfigureAwait(false);

                        if (messageText == null)
                        {
                            break; // webSocket is disconnected
                        }
                        Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' recived: " + messageText + ".");

                        sw.Restart();

                        messageText = WebSocketHandler(messageText);

                        await webSocket.WriteStringAsync(messageText, cancellation).ConfigureAwait(false);

                        Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' sent: " + messageText + ".");

                        sw.Stop();
                    }
                    catch (TaskCanceledException)
                    {
                        break;
                    }
                    catch (Exception readWriteError)
                    {
                        Console.WriteLine("An error occurred while reading/writing echo message.", readWriteError);
                        await webSocket.CloseAsync().ConfigureAwait(false);
                    }
                }
            }
            finally
            {
                webSocket.Dispose();
                Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' disconnected.");
            }
        }
Esempio n. 5
0
		static async Task HandleConnectionAsync(WebSocket ws, CancellationToken cancellation)
		{
			try
			{
				while (ws.IsConnected && !cancellation.IsCancellationRequested)
				{
					String msg = await ws.ReadStringAsync(cancellation).ConfigureAwait(false);
					Log("Message: " + msg);
					ws.WriteString(msg);
				}
			}
			catch (Exception aex)
			{
				Log("Error Handling connection: " + aex.GetBaseException().Message);
				try { ws.Close(); }
				catch { }
			}
			finally
			{
				ws.Dispose();
			}
		}
 private static void DisconnectWebSocket(WebSocket con)
 {
     Task.Run(() => con.Dispose());
 }
Esempio n. 7
0
        static async Task HandleConnectionAsync(WebSocket ws, CancellationToken cancellation)
        {
            try
            {
                IWebSocketLatencyMeasure l = ws as IWebSocketLatencyMeasure;

                PerformanceCounters.Connected.Increment();
                while (ws.IsConnected && !cancellation.IsCancellationRequested)
                {
                    String msg = await ws.ReadStringAsync(cancellation).ConfigureAwait(false);
                    PerformanceCounters.MessagesIn.Increment();

                    ws.WriteString(msg);
                    PerformanceCounters.MessagesOut.Increment();

                    PerformanceCounters.Delay.IncrementBy(l.Latency.Ticks * Stopwatch.Frequency / 10000);
                    PerformanceCounters.DelayBase.Increment();
                }
            }
            catch (TaskCanceledException)
            {

            }
            catch (Exception aex)
            {
                Log("Error Handling connection: " + aex.GetBaseException().Message);
                try { ws.Close(); }
                catch { }
            }
            finally
            {
                ws.Dispose();
                PerformanceCounters.Connected.Decrement();
            }
        }
Esempio n. 8
0
        private async Task HandleWebSocketAsync(WebSocket websocket)
        {
            try
            {
                OnConnect?.Invoke(websocket);

                while (websocket.IsConnected)
                {
                    var messageReadStream = await websocket.ReadMessageAsync(CancellationToken.None);
                    if (messageReadStream != null)
                    {
                        switch (messageReadStream.MessageType)
                        {
                            case WebSocketMessageType.Text:
                                using (var sr = new StreamReader(messageReadStream, Encoding.UTF8))
                                {
                                    var stringMessage = await sr.ReadToEndAsync();
                                    if (!string.IsNullOrEmpty(stringMessage))
                                    {
                                        OnPlainTextMessage?.Invoke(websocket, stringMessage);
                                    }
                                }
                                break;
                            case WebSocketMessageType.Binary:
                                using (var ms = new MemoryStream())
                                {
                                    await messageReadStream.CopyToAsync(ms);
                                    var data = ms.ToArray();
                                    if (data.Length > 0)
                                    {
                                        OnEncryptedMessage?.Invoke(websocket, data);
                                    }
                                }
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }
                    }
                }
                OnDisconnect?.Invoke(websocket);
            }
            catch (Exception ex)
            {
                OnError?.Invoke(websocket, ex);
            }
            finally
            {
                websocket.Dispose();
            }
        }
 public void Dispose()
 {
     _webSocket.Dispose();
 }
Esempio n. 10
0
        static async Task HandleConnectionAsync(WebSocket ws, CancellationToken cancellation)
        {
            bool isAuthenticated = false;
            try
            {
                Interlocked.Increment(ref PerformanceCounters.Connected);
                Console.WriteLine("Connected " + PerformanceCounters.Connected);

                await WaitForAuthenticateMessage(ws, cancellation).ConfigureAwait(false);
                isAuthenticated = true;

                await WaitForMessage(ws, cancellation).ConfigureAwait(false);
            }
            catch (TaskCanceledException)
            {

            }
            catch (Exception aex)
            {
                Log("Error Handling connection: " + aex.GetBaseException().Message);
                try { ws.Close(); }
                catch { }
            }
            finally
            {
                ws.Dispose();
                Interlocked.Increment(ref PerformanceCounters.Connected);
                Interlocked.Increment(ref PerformanceCounters.Accepted);
                if (isAuthenticated)
                {
                    Interlocked.Increment(ref PerformanceCounters.Authenticated);
                }

                Console.WriteLine("Connected " + PerformanceCounters.Connected);
                Console.WriteLine("Accepted " + PerformanceCounters.Accepted);
                Console.WriteLine("Authenticated " + PerformanceCounters.Authenticated);
            }
        }
Esempio n. 11
0
        static async Task HandleConnectionAsync(WebSocket ws, CancellationToken token)
        {
            try
            {
                PerformanceCounters.Connected.Increment();
                Byte[] buffer = new Byte[2046];
                Int32 readed;

                IWebSocketLatencyMeasure l = ws as IWebSocketLatencyMeasure;
                while (ws.IsConnected && !token.IsCancellationRequested)
                {
                    // await a message
                    using (var messageReader = await ws.ReadMessageAsync(token).ConfigureAwait(false))
                    {
                        if (messageReader == null)
                            continue; // disconnection

                        switch (messageReader.MessageType)
                        {
                            case WebSocketMessageType.Text:

                                PerformanceCounters.MessagesIn.Increment();
                                using (var messageWriter = ws.CreateMessageWriter(WebSocketMessageType.Text))
                                {
                                    readed = -1;
                                    Int32 r = 0;
                                    while(readed!=0)
                                    {
                                        readed = messageReader.Read(buffer, 0, buffer.Length);
                                        if (readed != 0)
                                        {
                                            messageWriter.Write(buffer, 0, readed);
                                            r += readed;
                                        }
                                    }
                                    await messageWriter.CloseAsync(token).ConfigureAwait(false);
                                }
                               PerformanceCounters.MessagesOut.Increment();

                                break;

                            case WebSocketMessageType.Binary:
                                using (var messageWriter = ws.CreateMessageWriter(WebSocketMessageType.Binary))
                                    await messageReader.CopyToAsync(messageWriter).ConfigureAwait(false);
                                break;
                        }
                    }

                    PerformanceCounters.Delay.IncrementBy(l.Latency.Ticks * Stopwatch.Frequency / 10000);
                    PerformanceCounters.DelayBase.Increment();
                }
            }
            catch (TaskCanceledException)
            {

            }
            catch (Exception aex)
            {
                var ex = aex.GetBaseException();
                _log.Error("HandleConnectionAsync", ex);
                Log("Error Handling connection: " + ex.GetType().Name + ": " + ex.Message);
                try { ws.Close(); }
                catch { }
            }
            finally
            {
                ws.Dispose();
                PerformanceCounters.Connected.Decrement();
            }
        }
        private async Task HandleWebSocketAsync(WebSocket websocket, ConnectionPrincipal connectionPrincipal)
        {
            VtortWebsocket soWebsocket = new VtortWebsocket(websocket, connectionPrincipal);
            try
            {
                Trace.TraceInformation("Server onConnect()");
                connectionPrincipal.OperationMessageListener.OnConnect(soWebsocket);

                while (websocket.IsConnected)
                {
                    var message = await websocket.ReadMessageAsync(CancellationToken.None)
                        .ConfigureAwait(false);
                    if (message != null)
                    {
                        switch (message.MessageType)
                        {
                            case WebSocketMessageType.Text:
                                using (var sr = new StreamReader(message, Encoding.UTF8))
                                {
                                    String msgContent = await sr.ReadToEndAsync();
                                    connectionPrincipal.OperationMessageListener.OnMessage(soWebsocket, msgContent);
                                }
                                break;
                            case WebSocketMessageType.Binary:
                                using (var ms = new MemoryStream())
                                {
                                    await message.CopyToAsync(ms);
                                    if (ms.Length > 0)
                                    {
                                        connectionPrincipal.OperationMessageListener.OnMessage(soWebsocket, ms.ToArray());
                                    }
                                }
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                connectionPrincipal.OperationMessageListener.OnError(ex);
            }
            finally
            {
                connectionPrincipal.OperationMessageListener.OnClose(soWebsocket, 1000, "");
                //Dispose before onClose is complete ???
                websocket.Dispose();
            }
        }
Esempio n. 13
0
 public void Dispose()
 {
     _messageReplies.Clear();
     _listener?.Dispose();
     OnDisconnect?.Invoke(this, EventArgs.Empty);
 }
Esempio n. 14
0
 async Task HandleConnectionAsync(WebSocket ws, CancellationToken cancellation)
 {
     try
     {
         while (ws.IsConnected && !cancellation.IsCancellationRequested)
         {
             // Get the JSON Message.
             String msg = await ws.ReadStringAsync(cancellation).ConfigureAwait(false);
             if (msg != null)
             {
                 // Convert the JSON String to a dictionary
                 Dictionary<string, dynamic> msgDict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(msg); ;
                 // If the dictionary contains a uniqueId, the message is a log-in request.
                 if (msgDict.ContainsKey("uniqueId"))
                 {
                     this.HandleMatchQueue(ws, msgDict);
                 }
                 // Message doesn't contain a UniqueId field.
                 else
                 {
                     // Make sure the websocket is in a match
                     if (wsToIdDictionary.ContainsKey(ws))
                     {
                         idToPlayerDictionary[wsToIdDictionary[ws]].currentMatch.AcceptMessage(ws, msgDict);
                     }
                 }
             }
         }
     }
     catch (Exception aex)
     {
         Console.WriteLine("Error Handling connection: " + aex.GetBaseException().Message);
         try { ws.Close(); }
         catch { }
     }
     // Theoretically, this happens when the ws disconnected, right?
     finally
     {
         if (wsToIdDictionary.ContainsKey(ws))
         {
             if (attackerQueue.Contains(wsToIdDictionary[ws]))
             {
                 string tempId = wsToIdDictionary[ws];
                 // loop ends when we find the id matching the ws we want to remove.
                 while (tempId != attackerQueue.Peek())
                 {
                     attackerQueue.Enqueue(attackerQueue.Dequeue());
                 }
                 attackerQueue.Dequeue();
             }
         }
         if (wsToIdDictionary.ContainsKey(ws))
         {
             if (defenderQueue.Contains(wsToIdDictionary[ws]))
             {
                 string tempId = wsToIdDictionary[ws];
                 // loop ends when we find the id matching the ws we want to remove.
                 while (tempId != defenderQueue.Peek())
                 {
                     defenderQueue.Enqueue(attackerQueue.Dequeue());
                 }
                 defenderQueue.Dequeue();
             }
         }
         if (wsToIdDictionary.ContainsKey(ws))
         {
             if (idToPlayerDictionary.ContainsKey(wsToIdDictionary[ws]))
             {
                 idToPlayerDictionary[wsToIdDictionary[ws]].currentMatch.ws_disconnected(ws);
             }
         }
         if (ws.IsConnected)
         {
             ws.Dispose();
         }
         
     }
 }