当前位置: 首页>>代码示例>>C#>>正文


C# WebSocket.CloseAsync方法代码示例

本文整理汇总了C#中System.Net.WebSockets.WebSocket.CloseAsync方法的典型用法代码示例。如果您正苦于以下问题:C# WebSocket.CloseAsync方法的具体用法?C# WebSocket.CloseAsync怎么用?C# WebSocket.CloseAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.WebSockets.WebSocket的用法示例。


在下文中一共展示了WebSocket.CloseAsync方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ProcessWebSocket

        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);
        }
开发者ID:McBits,项目名称:DungeonR,代码行数:30,代码来源:GameServer.cs

示例2: HandleSocket

        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();
            }
        }
开发者ID:hrbcksq,项目名称:websocket-chat,代码行数:28,代码来源:ChatHub.cs

示例3: Echo

 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);
 }
开发者ID:TerabyteX,项目名称:WebSockets,代码行数:11,代码来源:Startup.cs

示例4: EchoWebSocket

        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);
        }
开发者ID:leloulight,项目名称:Entropy,代码行数:15,代码来源:Startup.cs

示例5: DoWebSocketReceiveSendAsync

        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);
                }
            }
        }
开发者ID:Microsoft,项目名称:RTVS,代码行数:24,代码来源:WebSocketHelper.cs

示例6: ProcessWebSocket

        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);
        }
开发者ID:McBits,项目名称:DungeonR,代码行数:38,代码来源:GameServer.cs

示例7: ProcessWebSocketRequestAsync

        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();
            }
        }
开发者ID:GaneshBachhao,项目名称:SignalR,代码行数:76,代码来源:WebSocketHandler.cs

示例8: ReadSerializedMessage

        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;
        }
开发者ID:babilavena,项目名称:Chat-App,代码行数:28,代码来源:WebPushNotificationWebSocketsServer.ashx.cs

示例9: RunWebSocket

        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();
        }
开发者ID:kbekkenutte,项目名称:Owin.WebSocket,代码行数:29,代码来源:WebSocketConnection.cs


注:本文中的System.Net.WebSockets.WebSocket.CloseAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。