CloseAsync() 공개 추상적인 메소드

public abstract CloseAsync ( System closeStatus, string statusDescription, System cancellationToken ) : System.Threading.Tasks.Task
closeStatus System
statusDescription string
cancellationToken System
리턴 System.Threading.Tasks.Task
예제 #1
0
        public async Task ProcessWebSocket(HttpContext context, WebSocket webSocket)
        {
            var connection = new Connection(context, webSocket);
            Console.WriteLine("Connect: {0}", context.Connection.RemoteIpAddress);

            var cancelToken = CancellationToken.None;
            var buffer = new byte[1024];
            WebSocketReceiveResult received =
                await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);

            while (!webSocket.CloseStatus.HasValue)
            {
                string text = System.Text.Encoding.UTF8.GetString(buffer, 0, received.Count);

                Console.WriteLine("Recd: {0}", text);

                try
                {
                    Cmd.Parse(text, connection)?.Run();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unhandled exception: {0}", ex);
                }

                received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);
            }

            await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, cancelToken);
        }
예제 #2
0
        public override async Task CloseAsync()
        {
            if (IsConnected)
            {
                State = ChannelState.ClosedReceived;
            }

            if (socket != null)
            {
                try
                {
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal", CancellationToken.None);

                    socket.Dispose();
                    socket = null;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Fault closing Web socket server socket - {ex.Message}");
                }
            }



            OnClose?.Invoke(this, new ChannelCloseEventArgs(Id));
            await Task.CompletedTask;
        }
예제 #3
0
        private async Task HandleSocket(WebSocket socket)
        {
            var receiveBuffer = new byte[1024 * 4];
            try
            {
                var result = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                while (!socket.CloseStatus.HasValue)
                {
                    await Task.WhenAll(tasks: SocketsSingleton.Instance.SocketsBag.Where(x => x.State == WebSocketState.Open)
                        .Select(async x =>
                        {
                            await x.SendAsync(new ArraySegment<byte>(receiveBuffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
                        }));

                    SocketsSingleton.Instance.SocketsBag = new ConcurrentBag<WebSocket>(SocketsSingleton.Instance.SocketsBag.Where(x => x.State == WebSocketState.Open));
                    result = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                }
                await socket.CloseAsync(result.CloseStatus ?? WebSocketCloseStatus.EndpointUnavailable, result.CloseStatusDescription, CancellationToken.None);
            }
            catch (Exception exception)
            {
                Console.Write(exception);
            }
            finally
            {
                socket?.Dispose();
            }
        }
예제 #4
0
        /// <summary>
        /// 群发
        /// </summary>
        /// <param name="socketContext"></param>
        /// <returns></returns>
        public async Task ProcessChat(AspNetWebSocketContext socketContext)
        {
            //  SuperSocket:Session
            // 表示客户端发起请求的一个链接
            System.Net.WebSockets.WebSocket socket = socketContext.WebSocket;

            CancellationToken token = new CancellationToken();

            string socketGuid = Guid.NewGuid().ToString();

            OldChatManager.AddUser(socketGuid, UserName, socket, token);

            await OldChatManager.SengdMessage(token, UserName, "进入聊天室");

            while (socket.State == WebSocketState.Open)
            {
                ArraySegment <byte>    buffer = new ArraySegment <byte>(new byte[2048]);
                WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, token);

                string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); // 来自于客户端发送过来的消息内容

                if (result.MessageType == WebSocketMessageType.Close)
                {
                    OldChatManager.RemoveUser(socketGuid);
                    await OldChatManager.SengdMessage(token, UserName, "离开聊天室");

                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, token);
                }
                else
                {
                    await OldChatManager.SengdMessage(token, UserName, userMessage);
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Closes the transport, implementing the websocket close handshake.
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">The listener is not active</exception>
        protected override async Task PerformCloseAsync(CancellationToken cancellationToken)
        {
            await _closeSemaphore.WaitAsync(cancellationToken);

            try
            {
                // Awaits for the client to send the close connection frame.
                // If the session was clearly closed, the client should received the finished envelope and is closing the connection.
                using (var cts = new CancellationTokenSource(CloseTimeout))
                    using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token))
                    {
                        if (WebSocket.State == WebSocketState.Open ||
                            WebSocket.State == WebSocketState.CloseReceived)
                        {
                            await
                            WebSocket.CloseAsync(CloseStatus, CloseStatusDescription, linkedCts.Token)
                            .ConfigureAwait(false);
                        }
                    }

                if (!_receiveCts.IsCancellationRequested)
                {
                    _receiveCts.Cancel();
                }
            }
            finally
            {
                _closeSemaphore.Release();
            }
        }
        public static async Task ExecuteAPI(HttpContext context, System.Net.WebSockets.WebSocket webSocket)
        {
            var buffer = new byte[1024 * 20];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                string strRequest = Encoding.UTF8.GetString(buffer);
                string str        = strRequest.Replace("\0", string.Empty);
                string jsonStr    = string.Empty;

                try
                {
                    //Method
                    APIModel    apiModel = JsonSerializer.Deserialize <APIModel>(str);
                    string      apiName  = apiModel.Method;
                    BaseCommand command  = Activator.CreateInstance(CommandsDict[apiName]) as BaseCommand;
                    command.WebSocket = webSocket;
                    jsonStr           = command.Execute(str);
                    buffer            = Encoding.UTF8.GetBytes(jsonStr);
                    BaseRequestModel requestModel = JsonSerializer.Deserialize <BaseRequestModel>(str);
                    if (!string.IsNullOrEmpty(requestModel.Token))
                    {
                        if (command is UserLogoutCommand)
                        {
                            //do nothing
                        }
                        else
                        {
                            UserInfo userInfo = UserInfoDict[requestModel.Token];
                            userInfo.ActionTime = DateTime.Now;
                        }
                    }
                    else if (command is UserLoginCommand)
                    {
                        //do nothing
                    }
                }
                catch (Exception ex)
                {
                    ErrorResponseModel responseModel = new ErrorResponseModel();
                    responseModel.StatusCode = 0;
                    responseModel.ErrorCode  = "500";
                    responseModel.Message    = ex.Message;
                    jsonStr = JsonSerializer.Serialize(responseModel);
                    buffer  = Encoding.UTF8.GetBytes(jsonStr);
                }

                await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, jsonStr.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);

                buffer = new byte[1024 * 20];
                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
예제 #7
0
        internal async Task RunAsync()
        {
            await _logger.InfoAsync($"Connected");

            var token = _cancelToken.Token;

            try
            {
                var segment = new ArraySegment <byte>(_inBuffer);

                //Send HELLO
                await SendAsync(GatewayOpCode.Hello, new HelloEvent { HeartbeatInterval = 15000 }).ConfigureAwait(false);

                while (_socket.State == WebSocketState.Open)
                {
                    var result = await _socket.ReceiveAsync(segment, token).ConfigureAwait(false);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        await _logger.WarningAsync($"Received Close {result.CloseStatus} ({result.CloseStatusDescription ?? "No Reason"})").ConfigureAwait(false);
                    }
                    else
                    {
                        await _logger.InfoAsync($"Received {result.Count} bytes");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                try { await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).ConfigureAwait(false); }
                catch { }
            }
            catch (Exception ex)
            {
                try { await _socket.CloseAsync(WebSocketCloseStatus.InternalServerError, ex.Message, CancellationToken.None).ConfigureAwait(false); }
                catch { }
            }
            finally
            {
                await _logger.InfoAsync($"Disconnected");
            }
        }
예제 #8
0
 private async Task Echo(WebSocket webSocket)
 {
     byte[] buffer = new byte[1024 * 4];
     var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
     while (!result.CloseStatus.HasValue)
     {
         await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
         result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
     }
     await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
 }
예제 #9
0
 /// <summary>
 /// Close the connection.
 /// </summary>
 public async void Close()
 {
     // Close the connection.
     if (_webSocket != null)
     {
         try
         {
             // Close the connection.
             await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
         }
         catch (Exception ex) { _lastError = ex; }
     }
 }
예제 #10
0
 protected override async void OnClose(CancellationToken ct)
 {
     try
     {
         await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Session Ended", ct);
     }
     catch { }
     try
     {
         await _webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Session Ended", ct);
     }
     catch { }
 }
예제 #11
0
        private static async Task Echo(HttpContext context, System.Net.WebSockets.WebSocket webSocket)
        {
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
예제 #12
0
        private async Task EchoWebSocket(WebSocket webSocket)
        {
            byte[] buffer = new byte[1024];
            WebSocketReceiveResult received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

            while (!webSocket.CloseStatus.HasValue)
            {
                // Echo anything we receive
                await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, received.Count), received.MessageType, received.EndOfMessage, CancellationToken.None);

                received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            }

            await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, CancellationToken.None);
        }
예제 #13
0
        private static async Task DoWebSocketReceiveSendAsync(WebSocket receiver, WebSocket sender, CancellationToken ct) {
            if (receiver == null || sender == null) {
                return;
            }

            ArraySegment<byte> receiveBuffer = new ArraySegment<byte>(new byte[65335]);
            while (receiver.State == WebSocketState.Open && sender.State == WebSocketState.Open) {
                if (ct.IsCancellationRequested) {
                    receiver.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", CancellationToken.None).SilenceException<WebSocketException>().DoNotWait();
                    sender.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", CancellationToken.None).SilenceException<WebSocketException>().DoNotWait();
                    return;
                }

                WebSocketReceiveResult result = await receiver.ReceiveAsync(receiveBuffer, ct);

                byte[] data = await receiveBuffer.ToByteArrayAsync(result.Count);
                ArraySegment<byte> sendBuffer = new ArraySegment<byte>(data);
                await sender.SendAsync(sendBuffer, result.MessageType, result.EndOfMessage, ct);

                if (result.MessageType == WebSocketMessageType.Close) {
                    await receiver.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", ct);
                }
            }
        }
예제 #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="webSocket"></param>
        /// <returns></returns>
        public async Task ConnectClientAsync(System.Net.WebSockets.WebSocket webSocket)
        {
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                string content = Encoding.UTF8.GetString(buffer);

                await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }

            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
예제 #15
0
        private async Task DoPull(WebSocket socket, CancellationToken cancellationToken)
        {
            try
            {
                var buf = new Byte[4 * 1024];
                while (!cancellationToken.IsCancellationRequested && socket.State == WebSocketState.Open)
                {
                    var data = await socket.ReceiveAsync(new ArraySegment <Byte>(buf), cancellationToken);

                    var cmd = buf.ToStr(null, 0, data.Count).ToJsonEntity <CommandModel>();
                    if (cmd != null)
                    {
                        XTrace.WriteLine("Got Command: {0}", cmd.ToJson());
                        if (cmd.Expire.Year < 2000 || cmd.Expire > DateTime.Now)
                        {
                            switch (cmd.Command)
                            {
                            case "Deploy":
                                // 发布中心通知有应用需要部署,马上执行一次心跳,拉取最新应用信息
                                _ = Task.Run(Ping);
                                break;

                            default:
                                var rs = CommandQueue.Publish(cmd.Command, cmd);
                                if (rs != null)
                                {
                                    await ReportAsync(cmd.Id, rs);
                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }

            if (socket.State == WebSocketState.Open)
            {
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "finish", default);
            }
        }
        private async Task HandleWebSocket(WebSocketContext wsContext)
        {
            var socketId = Guid.NewGuid().ToString();

            System.Net.WebSockets.WebSocket webSocket = wsContext.WebSocket;
            try
            {
                _sockets.TryAdd(socketId, webSocket);
                byte[] receiveBuffer = new byte[1024 * 4];
                while (webSocket.State == WebSocketState.Open)
                {
                    //var msg = Encoding.UTF8.GetBytes(WebSocketSerivce.GetNewOrders());
                    //await webSocket.SendAsync(new ArraySegment<byte>(msg, 0, msg.Length), WebSocketMessageType.Text,
                    //    true, CancellationToken.None);

                    WebSocketReceiveResult receiveResult =
                        await webSocket.ReceiveAsync(new ArraySegment <byte>(receiveBuffer), CancellationToken.None);

                    if (receiveResult.MessageType == WebSocketMessageType.Close)
                    {
                        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);

                        _sockets.TryRemove(socketId, out System.Net.WebSockets.WebSocket removedSocket);
                    }
                    else
                    {
                        foreach (var socket in _sockets.Where(x => x.Key != socketId).Select(x => x.Value))
                        {
                            await socket.SendAsync(new ArraySegment <byte>(receiveBuffer, 0, receiveResult.Count),
                                                   WebSocketMessageType.Text, receiveResult.EndOfMessage, CancellationToken.None);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e);
            }
            finally
            {
                webSocket?.Dispose();
            }
        }
예제 #17
0
        async Task websocketHandle(System.Net.WebSockets.WebSocket socket, HttpRequest request)
        {
            var bs = new byte[204800];

            while (true)
            {
                if (socket.State == System.Net.WebSockets.WebSocketState.Open)
                {
                    try
                    {
                        ArraySegment <byte>    buffer = new ArraySegment <byte>(bs);
                        WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);

                        if (result.Count == 0)
                        {
                            //客户端要求关闭
                            socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None).Wait();
                            continue;
                        }
                        StringBuilder str = new StringBuilder();
                        foreach (var item in request.Headers)
                        {
                            foreach (var v in item.Value)
                            {
                                str.Append($"{item.Key}={v}\r\n");
                            }
                        }
                        byte[] sendbackBs = System.Text.Encoding.UTF8.GetBytes(str.ToString());

                        buffer = new ArraySegment <byte>(sendbackBs);
                        await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                    catch
                    {
                    }
                }
                else
                {
                    break;
                }
            }
        }
예제 #18
0
        private static async Task ListenToClients(HttpContext context, System.Net.WebSockets.WebSocket socket)
        {
            var buffer = new byte[6 * 1024];
            WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                var content = Encoding.UTF8.GetString(buffer).Substring(0, result.Count);

                try
                {
                    CallServerMethod(content);
                }
                catch { }

                result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }

            await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
예제 #19
0
 private void InternalReceive()
 {
     Task.Run(async() =>
     {
         byte[] _buffer = new byte[WebSocketProtocol.BUFFER_SIZE];
         while (Connected && !connectionManager.Token.IsCancellationRequested)
         {
             ArraySegment <byte> buffer = new ArraySegment <byte>(_buffer);
             var received = await socket.ReceiveAsync(buffer, connectionManager.Token);
             if (received.MessageType != WebSocketMessageType.Close)
             {
                 byte[] result = new byte[received.Count];
                 Array.ConstrainedCopy(buffer.Array, 0, result, 0, received.Count);
                 receivedPackages.Enqueue(result);
             }
             else
             {
                 await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "close", connectionManager.Token);
             }
         }
     });
 }
예제 #20
0
        public async Task ProcessWebSocket(HttpContext context, WebSocket webSocket)
        {
            var connection = new Connection(context, webSocket);
            _allConnections.Add(connection);
            Console.WriteLine("Connect: {0}", context.Connection.RemoteIpAddress);

            var cancelToken = CancellationToken.None;
            var buffer = new byte[1024];
            WebSocketReceiveResult received =
                await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);

            while (!webSocket.CloseStatus.HasValue)
            {
                string text = System.Text.Encoding.UTF8.GetString(buffer, 0, received.Count);

                Console.WriteLine("Recd: {0}", text);

                try
                {
                    var cmd = Cmd.Parse(text, connection);
                    if (cmd != null) {
                        // TODO: Remove these dependencies from Cmd
                        cmd.SpawnDaemon = _spawnDaemon;
                        cmd.DecayDaemon = _decayDaemon;
                        cmd.Run();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unhandled exception: {0}", ex);
                }

                received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);
            }

            _allConnections.Remove(connection);
            await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, cancelToken);
        }
예제 #21
0
        public void RemoveSocket(string connectionGUID, System.Net.WebSockets.WebSocket socket)
        {
            lock (_socketsList)
            {
                HashSet <System.Net.WebSockets.WebSocket> sockets;
                if (!_socketsList.TryGetValue(connectionGUID, out sockets))
                {
                    return;
                }

                lock (sockets)
                {
                    sockets.Remove(socket);

                    if (sockets.Count == 0)
                    {
                        _socketsList.Remove(connectionGUID);
                    }
                }
            }
            socket.CloseAsync(closeStatus: WebSocketCloseStatus.NormalClosure,
                              statusDescription: "Closed by the WebSocketManager",
                              cancellationToken: CancellationToken.None);
        }
예제 #22
0
        private static async Task HandleMessage(System.Net.WebSockets.WebSocket webSocket)
        {
            //Gets the current WebSocket object.

            /*We define a certain constant which will represent
             * size of received data. It is established by us and
             * we can set any value. We know that in this case the size of the sent
             * data is very small.
             */
            const int maxMessageSize = 1024;

            //Buffer for received bits.
            var receivedDataBuffer = new ArraySegment <Byte>(new Byte[maxMessageSize]);

            var cancellationToken = new CancellationToken();


            WebSocketHelper webSocketHandler = new WebSocketHelper(webSocket, /*webSocketContext, */ cancellationToken);
            var             messageHandler   = WebSocketConfig.WebSocketMessageHandlerFunc.Invoke();

            while (webSocket.State == WebSocketState.Open)
            {
                //var incoming = await this._socket.ReceiveAsync(seg, CancellationToken.None);
                //var outgoing = new ArraySegment<byte>(buffer, 0, incoming.Count);
                //await this._socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);


                //Reads data.
                WebSocketReceiveResult webSocketReceiveResult =
                    await webSocket.ReceiveAsync(receivedDataBuffer, cancellationToken).ConfigureAwait(false);

                //If input frame is cancelation frame, send close command.
                if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
                {
                    if (WebSocketConfig.WebSocketMessageHandlerFunc != null)
                    {
                        await messageHandler.OnDisConnected(webSocketHandler).ConfigureAwait(false);//调用MessageHandler
                    }

                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,
                                               String.Empty, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    byte[] payloadData = receivedDataBuffer.Array
                                         .Where(b => b != 0)
                                         .Take(webSocketReceiveResult.Count)
                                         .ToArray();

                    if (WebSocketConfig.WebSocketMessageHandlerFunc != null)
                    {
                        //Because we know that is a string, we convert it.
                        string receiveString =
                            //System.Text.Encoding.UTF8.GetString(payloadData, 0, payloadData.Length);
                            System.Text.Encoding.UTF8.GetString(payloadData, 0, payloadData.Length);
                        try
                        {
                            ReceivedMessage receivedMessage;
                            try
                            {
                                receivedMessage = new ReceivedMessage()
                                {
                                    Message = receiveString// + " | 系统错误:" + e.Message
                                };


#if NET45
                                JavaScriptSerializer js = new JavaScriptSerializer();
                                receivedMessage = js.Deserialize <ReceivedMessage>(receiveString);
#else
                                receivedMessage = Newtonsoft.Json.JsonConvert.DeserializeObject <ReceivedMessage>(receiveString);
#endif
                            }
                            catch (Exception e)
                            {
                                receivedMessage = new ReceivedMessage()
                                {
                                    Message = receiveString// + " | 系统错误:" + e.Message
                                };
                            }
                            await messageHandler.OnMessageReceiced(webSocketHandler, receivedMessage, receiveString).ConfigureAwait(false);//调用MessageHandler
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            }
        }
예제 #23
0
 public static async Task CloseAsync(this WebSocket client, WebSocketCloseStatus state)
 {
     await client.CloseAsync(state, "", CancellationToken.None);
 }
예제 #24
0
        /// <summary>
        /// Awaitable task that reads incoming messages from the WebSocket.
        /// This is a blocking method
        /// </summary>
        /// <returns></returns>
        public async Task <ConnectionResult> ReadLoopAsync(CancellationToken ct)
        {
            while (!ct.IsCancellationRequested && !_disconnecting)
            {
                if (_ws.State != WebSocketState.Open)
                {
                    TraceEvent(
                        "(ReadLoopAsync) Invalid attempt to read a closed socket",
                        EventIdentifiers.WS_ERR_READ_SOCK_CLOSE_ASYNC,
                        TraceEventType.Error
                        );
                    throw new InvalidOperationException("Websocket is not open");
                }

                if (ct.IsCancellationRequested)
                {
                    TraceEvent(
                        "(ReadLoopAsync) Operation cancelled",
                        EventIdentifiers.WS_WAR_CANC_READ,
                        TraceEventType.Warning
                        );
                    ct.ThrowIfCancellationRequested();
                }

                await _sem.WaitAsync(ct);

                WebSocketReceiveResult res;
                ArraySegment <byte>    buf = new ArraySegment <byte>(new byte[1024]);

                res = await _ws.ReceiveAsync(buf, ct);

                _sem.Release();
                //We don't know how long the receive task has waited, so check for cancellation again
                if (ct.IsCancellationRequested)
                {
                    TraceEvent(
                        "(ReadLoopAsync) Operation cancelled",
                        EventIdentifiers.WS_WAR_CANC_READ_ASYNC,
                        TraceEventType.Warning
                        );
                    ct.ThrowIfCancellationRequested();
                }

                if (res.MessageType == WebSocketMessageType.Close)
                {
                    _disconnecting = true;
                    TraceEvent(
                        $"(ReadLoopAsync) Close request: [{res.CloseStatus}] {res.CloseStatusDescription}",
                        EventIdentifiers.WS_INF_CONN_CLOSE_REQ,
                        TraceEventType.Information
                        );
                    await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close request acknowledged", ct);

                    TraceEvent(
                        "(ReadLoopAsync) Socket disconnected",
                        EventIdentifiers.WS_INF_CONN_CLOSE,
                        TraceEventType.Information
                        );
                    return(ConnectionResult.Disconnecting);
                }

                if (!res.EndOfMessage)
                {
                    _rQ.Enqueue(buf.Take(res.Count));
                    continue;
                }

                List <byte> msg = new List <byte>();
                while (!_rQ.IsEmpty)
                {
                    _rQ.TryDequeue(out IEnumerable <byte> result);
                    msg.AddRange(result);
                }

                msg.AddRange(buf.Take(res.Count));

                TraceEvent(
                    $"(ReadLoopAsync) Received bytes [ len: {res.Count} ]",
                    EventIdentifiers.WS_VER_RBYTES_ASYNC,
                    TraceEventType.Verbose
                    );

                if (res.MessageType == WebSocketMessageType.Binary)
                {
                    OnBinaryMessage?.Invoke(this, new BinaryMessageEventArgs(msg.ToArray()));
                }
                else
                {
                    string strMsg = Encoding.UTF8.GetString(msg.ToArray());
                    OnTextMessage?.Invoke(this, new StringMessageEventArgs(strMsg));
                }
            }

            if (ct.IsCancellationRequested)
            {
                TraceEvent(
                    "(ReadLoopAsync) Operation cancelled",
                    EventIdentifiers.WS_WAR_CANC_READ_ASYNC,
                    TraceEventType.Warning
                    );
                ct.ThrowIfCancellationRequested();
            }

            TraceEvent(
                "(ReadLoopAsync) Socket disconnecting",
                EventIdentifiers.WS_INF_CONN_CLOSE,
                TraceEventType.Information
                );
            return(ConnectionResult.Disconnecting);
        }
예제 #25
0
        /// <summary>
        /// 部分Handler过程参考:http://www.cnblogs.com/lookbs/p/MVC-IMG.html
        /// </summary>
        /// <param name="webSocketContext"></param>
        /// <returns></returns>
        public static async Task WebSocketRequestHandler(AspNetWebSocketContext webSocketContext)
        {
            //Gets the current WebSocket object.
            System.Net.WebSockets.WebSocket webSocket = webSocketContext.WebSocket;

            /*We define a certain constant which will represent
             * size of received data. It is established by us and
             * we can set any value. We know that in this case the size of the sent
             * data is very small.
             */
            const int maxMessageSize = 1024;

            //Buffer for received bits.
            var receivedDataBuffer = new ArraySegment <Byte>(new Byte[maxMessageSize]);

            var cancellationToken = new CancellationToken();


            WebSocketHelper webSocketHandler = new WebSocketHelper(webSocketContext, cancellationToken);
            var             messageHandler   = WebSocketConfig.WebSocketMessageHandlerFunc.Invoke();

            if (webSocket.State == WebSocketState.Connecting)
            {
                if (WebSocketConfig.WebSocketMessageHandlerFunc != null)
                {
                    await messageHandler.OnConnecting(webSocketHandler);//调用MessageHandler
                }
            }

            //Checks WebSocket state.
            while (webSocket.State == WebSocketState.Open)
            {
                //Reads data.
                WebSocketReceiveResult webSocketReceiveResult =
                    await webSocket.ReceiveAsync(receivedDataBuffer, cancellationToken);

                //If input frame is cancelation frame, send close command.
                if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
                {
                    if (WebSocketConfig.WebSocketMessageHandlerFunc != null)
                    {
                        await messageHandler.OnDisConnected(webSocketHandler);//调用MessageHandler
                    }

                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,
                                               String.Empty, cancellationToken);
                }
                else
                {
                    byte[] payloadData = receivedDataBuffer.Array
                                         .Where(b => b != 0)
                                         .Take(webSocketReceiveResult.Count)
                                         .ToArray();

                    if (WebSocketConfig.WebSocketMessageHandlerFunc != null)
                    {
                        //Because we know that is a string, we convert it.
                        string receiveString =
                            System.Text.Encoding.UTF8.GetString(payloadData, 0, payloadData.Length);
                        try
                        {
                            ReceivedMessage receivedMessage;
                            try
                            {
                                receivedMessage = new ReceivedMessage()
                                {
                                    Message = receiveString// + " | 系统错误:" + e.Message
                                };

                                receivedMessage = Newtonsoft.Json.JsonConvert.DeserializeObject <ReceivedMessage>(receiveString);
                            }
                            catch (Exception e)
                            {
                                receivedMessage = new ReceivedMessage()
                                {
                                    Message = receiveString// + " | 系统错误:" + e.Message
                                };
                            }
                            await messageHandler.OnMessageReceiced(webSocketHandler, receivedMessage, receiveString);//调用MessageHandler
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            }
        }
예제 #26
0
 public override async Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
 {
     await _webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken);
 }
예제 #27
0
 public Task Close(WebSocketCloseStatus closeStatus, string closeDescription, CancellationToken cancelToken)
 {
     return(mWebSocket.CloseAsync(closeStatus, closeDescription, cancelToken));
 }
 public override Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription,
                                 CancellationToken cancellationToken)
 {
     ThrowIfNotConnected();
     return(innerWebSocket.CloseAsync(closeStatus, statusDescription, cancellationToken));
 }
        private async Task RunWebSocket(IDictionary<string, object> websocketContext)
        {
            // Try to get the websocket context from the environment
            object value;
            if (!websocketContext.TryGetValue(typeof(WebSocketContext).FullName, out value))
            {
                throw new InvalidOperationException("Unable to find web socket context");
            }

            mWebSocket = ((WebSocketContext)value).WebSocket;

            OnOpen();

            var buffer = new byte[MaxMessageSize];
            do
            {
                var received = await ReceiveOneMessage(buffer);
                if (received.Item1.Count > 0)
                    OnMessageReceived(received.Item1, received.Item2);
            }
            while (!mWebSocket.CloseStatus.HasValue);

            await mWebSocket.CloseAsync(mWebSocket.CloseStatus.GetValueOrDefault(WebSocketCloseStatus.Empty),
                mWebSocket.CloseStatusDescription, mCancellToken.Token);

            mCancellToken.Cancel();

            OnClose();
        }
예제 #30
0
 public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) => _webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken);
        private async Task<String> ReadSerializedMessage(WebSocket socket)
        {
            var byteBuffer = new byte[MaxBufferSize];
            var arraySegmentBuffer = new ArraySegment<byte>(byteBuffer);
            WebSocketReceiveResult result = await socket.ReceiveAsync(arraySegmentBuffer, CancellationToken.None);
            string ret = "";

            if (result.MessageType == WebSocketMessageType.Close)
            {
                await
                    socket.CloseAsync(result.CloseStatus.GetValueOrDefault(), result.CloseStatusDescription,
                        CancellationToken.None);
            }
            else
            {
                int messageSize = 0;

                for (messageSize = result.Count; !result.EndOfMessage; messageSize += result.Count)
                {
                    result = await socket.ReceiveAsync(new ArraySegment<byte>(byteBuffer, messageSize, MaxBufferSize - messageSize), CancellationToken.None);
                }
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    ret = Encoding.UTF8.GetString(byteBuffer, 0, messageSize);
                }
            }
            return ret;
        }
예제 #32
0
        internal async Task ProcessWebSocketRequestAsync(WebSocket webSocket, CancellationToken disconnectToken, Func<object, Task<WebSocketMessage>> messageRetriever, object state)
        {
            bool closedReceived = false;

            try
            {
                // first, set primitives and initialize the object
                WebSocket = webSocket;
                OnOpen();

                // dispatch incoming messages
                while (!disconnectToken.IsCancellationRequested && !closedReceived)
                {
                    WebSocketMessage incomingMessage = await messageRetriever(state);
                    switch (incomingMessage.MessageType)
                    {
                        case WebSocketMessageType.Binary:
                            OnMessage((byte[])incomingMessage.Data);
                            break;

                        case WebSocketMessageType.Text:
                            OnMessage((string)incomingMessage.Data);
                            break;

                        default:
                            closedReceived = true;

                            // If we received an incoming CLOSE message, we'll queue a CLOSE frame to be sent.
                            // We'll give the queued frame some amount of time to go out on the wire, and if a
                            // timeout occurs we'll give up and abort the connection.
                            await Task.WhenAny(CloseAsync(), Task.Delay(_closeTimeout));
                            break;
                    }
                }

            }
            catch (OperationCanceledException ex)
            {
                // ex.CancellationToken never has the token that was actually cancelled
                if (!disconnectToken.IsCancellationRequested)
                {
                    Error = ex;
                    OnError();
                }
            }
            catch (ObjectDisposedException)
            {
                // If the websocket was disposed while we were reading then noop
            }
            catch (Exception ex)
            {
                if (IsFatalException(ex))
                {
                    Error = ex;
                    OnError();
                }
            }

            try
            {
                if (WebSocket.State == WebSocketState.Closed ||
                    WebSocket.State == WebSocketState.Aborted)
                {
                    // No-op if the socket is already closed or aborted
                }
                else
                {
                    // Close the socket
                    await WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                }
            }
            finally
            {
                OnClose();
            }
        }
예제 #33
0
        private static async Task Echo(System.Net.WebSockets.WebSocket webSocket)
        {
            WebSocketReceiveResult wResult;

            {
                byte[] buffer = new byte[size];
                do
                {
                    try
                    {
                        wResult = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                        var str = getStrFromByte(ref buffer);
                        if (str == "allMap")
                        {
                            Dictionary <string, bool> Cs            = new Dictionary <string, bool>();
                            List <object>             listOfCrosses = new List <object>();
                            Dictionary <string, Dictionary <int, OssModel.SaveRoad.RoadInfo> > result;
                            Program.dt.GetData(out result);
                            List <double[]> meshPoints = new List <double[]>();
                            //   List<int> colors = new List<int>();
                            foreach (var item in result)
                            {
                                foreach (var itemj in item.Value)
                                {
                                    var value = itemj.Value;
                                    var ps    = getRoadRectangle(value, item.Value);
                                    meshPoints.Add(ps);


                                    for (var i = 0; i < value.Cross1.Length; i++)
                                    {
                                        var cross = value.Cross1[i];
                                        var key   = cross.RoadCode1.CompareTo(cross.RoadCode2) > 0 ?
                                                    $"{cross.RoadCode1}_{cross.RoadOrder1}_{cross.RoadCode2}_{cross.RoadOrder2}" :
                                                    $"{cross.RoadCode2}_{cross.RoadOrder2}_{cross.RoadCode1}_{cross.RoadOrder1}";
                                        if (Cs.ContainsKey(key))
                                        {
                                        }
                                        else
                                        {
                                            Cs.Add(key, false);
                                            listOfCrosses.Add(new { lon = cross.BDLongitude, lat = cross.BDLatitude, state = cross.CrossState });
                                        }
                                    }
                                    //value.Cross1
                                }
                            }
                            {
                                var msg      = Newtonsoft.Json.JsonConvert.SerializeObject(new { reqMsg = str, t = "road", obj = meshPoints });
                                var sendData = Encoding.UTF8.GetBytes(msg);
                                await webSocket.SendAsync(new ArraySegment <byte>(sendData, 0, sendData.Length), wResult.MessageType, true, CancellationToken.None);
                            }
                            {
                                var msg      = Newtonsoft.Json.JsonConvert.SerializeObject(new { reqMsg = str, t = "cross", obj = listOfCrosses });
                                var sendData = Encoding.UTF8.GetBytes(msg);
                                await webSocket.SendAsync(new ArraySegment <byte>(sendData, 0, sendData.Length), wResult.MessageType, true, CancellationToken.None);
                            }

                            //foreach (var item in result)
                            //{
                            //    foreach (var itemj in item.Value)
                            //    {
                            //        var value = itemj.Value;
                            //        var ps = getCrossPoints(value, result);
                            //        meshPoints.Add(ps);

                            //    }
                            //}
                        }
                    }
                    catch
                    {
                        // Console.WriteLine($"step2:webSockets数量:{   BufferImage.webSockets.Count}");
                        return;
                    }
                }while (!wResult.CloseStatus.HasValue);
                try
                {
                    await webSocket.CloseAsync(wResult.CloseStatus.Value, wResult.CloseStatusDescription, CancellationToken.None);
                }
                catch
                {
                    return;
                }
            };
        }