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


C# WebSocket.ReceiveAsync方法代码示例

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


在下文中一共展示了WebSocket.ReceiveAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: ReadMessageAsync

        public static async Task<WebSocketMessage> ReadMessageAsync(WebSocket webSocket, byte[] buffer, int maxMessageSize)
        {
            ArraySegment<byte> arraySegment = new ArraySegment<byte>(buffer);

            WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false);
            // special-case close messages since they might not have the EOF flag set
            if (receiveResult.MessageType == WebSocketMessageType.Close)
            {
                return new WebSocketMessage(null, WebSocketMessageType.Close);
            }

            if (receiveResult.EndOfMessage)
            {
                // we anticipate that single-fragment messages will be common, so we optimize for them
                switch (receiveResult.MessageType)
                {
                    case WebSocketMessageType.Binary:
                        return new WebSocketMessage(BufferSliceToByteArray(buffer, receiveResult.Count), WebSocketMessageType.Binary);

                    case WebSocketMessageType.Text:
                        return new WebSocketMessage(BufferSliceToString(buffer, receiveResult.Count), WebSocketMessageType.Text);

                    default:
                        throw new Exception("This code path should never be hit.");
                }
            }
            else
            {
                // for multi-fragment messages, we need to coalesce
                ByteBuffer bytebuffer = new ByteBuffer(maxMessageSize);
                bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
                WebSocketMessageType originalMessageType = receiveResult.MessageType;

                while (true)
                {
                    // loop until an error occurs or we see EOF
                    receiveResult = await webSocket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false);
                    if (receiveResult.MessageType != originalMessageType)
                    {
                        throw new InvalidOperationException("Incorrect message type");
                    }

                    bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
                    if (receiveResult.EndOfMessage)
                    {
                        switch (receiveResult.MessageType)
                        {
                            case WebSocketMessageType.Binary:
                                return new WebSocketMessage(bytebuffer.GetByteArray(), WebSocketMessageType.Binary);

                            case WebSocketMessageType.Text:
                                return new WebSocketMessage(bytebuffer.GetString(), WebSocketMessageType.Text);

                            default:
                                throw new Exception("This code path should never be hit.");
                        }
                    }
                }
            }
        }
开发者ID:TerenceLewis,项目名称:SignalR,代码行数:60,代码来源:WebSocketMessageReader.cs

示例4: ReceiveAsync

 static async Task<Message> ReceiveAsync(WebSocket ws)
 {
     byte[] buffer = new byte[4096];
     var seg = new ArraySegment<byte>(buffer);
     var result = await ws.ReceiveAsync(seg, CancellationToken.None);
     return Message.Deserialize(new ArraySegment<byte>(buffer, 0, result.Count));
 }
开发者ID:hpatel98,项目名称:SCAMP,代码行数:7,代码来源:Program.cs

示例5: 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

示例6: 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

示例7: EchoAsync

        public async Task EchoAsync(WebSocket webSocket)
        {
            var buffer = new ArraySegment<byte>(new byte[8192]);
            for (; ;)
            {
                var result = await webSocket.ReceiveAsync(
                    buffer,
                    CancellationToken.None);

                if (result.MessageType == WebSocketMessageType.Close)
                {
                    return;
                }
                else if (result.MessageType == WebSocketMessageType.Text)
                {
                    Console.WriteLine("{0}", System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count));
                }

                await webSocket.SendAsync(
                    new ArraySegment<byte>(buffer.Array, 0, result.Count),
                    result.MessageType,
                    result.EndOfMessage,
                    CancellationToken.None);
            }
        }
开发者ID:fakedob,项目名称:KestrelHttpServer,代码行数:25,代码来源:Startup.cs

示例8: keyboardHandler

 private void keyboardHandler(WebSocket ws)
 {
     byte[] buffer = new byte[4096 * 4096];
     var task = ws.ReceiveAsync(new ArraySegment<byte>(buffer), System.Threading.CancellationToken.None).ContinueWith((ReceiveResult) =>
     {
         string s = System.Text.Encoding.ASCII.GetString(buffer);
         s = s.TrimEnd('\0', ' ');
         foreach (string keyboardCmd in s.Split(' ', '\0'))
         {
             string cmd = keyboardCmd.ToLower().Trim();
             if (keyboardCmd.StartsWith("up/") && keyboardCmd.Length > "up/".Length)
             {
                 Keyboard.KeyUp(int.Parse(keyboardCmd.Substring("up/".Length), System.Globalization.NumberStyles.AllowHexSpecifier));
             }
             if (keyboardCmd.StartsWith("down/") && keyboardCmd.Length > "down/".Length)
             {
                 Keyboard.KeyDown(int.Parse(keyboardCmd.Substring("down/".Length), System.Globalization.NumberStyles.AllowHexSpecifier));
             }
             if (keyboardCmd.StartsWith("tap/") && keyboardCmd.Length > "tap/".Length)
             {
                 Keyboard.KeyTap(int.Parse(keyboardCmd.Substring("tap/".Length), System.Globalization.NumberStyles.AllowHexSpecifier));
             }
         }
         keyboardHandler(ws);
     });
 }
开发者ID:sundhaug92,项目名称:librgc,代码行数:26,代码来源:WebServer.cs

示例9: WebSocketHost

        private WebSocketHost(WebSocket webSocket)
        {
            _webSocket = webSocket;
            _buffer = new byte[1024];

            // Start listening for incoming messages
            _webSocket.ReceiveAsync(new ArraySegment<byte>(_buffer), CancellationToken.None).ContinueWith(ReceiveMessage);
        }
开发者ID:JayBeavers,项目名称:WebSocketTraceListener,代码行数:8,代码来源:WebSocketHost.cs

示例10: 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

示例11: KeepAlive

        private async Task KeepAlive(WebSocket connection)
        {
            while (connection.State == WebSocketState.Open)
            {
                var token = CancellationToken.None;
                var buffer = new ArraySegment<byte>(new byte[4096]);
                var received = await connection.ReceiveAsync(buffer, token);

                switch (received.MessageType)
                {
                    case WebSocketMessageType.Text:
                        var request = Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count);
                        SocketMessage receive = JsonConvert.DeserializeObject<SocketMessage>(request);
                        await Map.Receive(receive);
                        break;
                }
            }
        }
开发者ID:marviobezerra,项目名称:XCommon,代码行数:18,代码来源:ConnectionManager.cs

示例12: WebSocketToPipeWorker

        private static async Task WebSocketToPipeWorker(WebSocket socket, IMessagePipeEnd pipe, CancellationToken cancellationToken) {
            const int blockSize = 0x10000;
            var buffer = new MemoryStream(blockSize);

            while (true) {
                cancellationToken.ThrowIfCancellationRequested();

                int index = (int)buffer.Length;
                buffer.SetLength(index + blockSize);

                var wsrr = await socket.ReceiveAsync(new ArraySegment<byte>(buffer.GetBuffer(), index, blockSize), cancellationToken);
                buffer.SetLength(index + wsrr.Count);

                if (wsrr.CloseStatus != null) {
                    break;
                } else if (wsrr.EndOfMessage) {
                    pipe.Write(buffer.ToArray());
                    buffer.SetLength(0);
                }
            }
        }
开发者ID:Microsoft,项目名称:RTVS,代码行数:21,代码来源:WebSocketPipeAction.cs

示例13: 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

示例14: ReadMessageAsync

        public static async Task<WebSocketMessage> ReadMessageAsync(WebSocket webSocket, int bufferSize, int? maxMessageSize, CancellationToken disconnectToken)
        {
            WebSocketMessage message;

            // Read the first time with an empty array
            WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(_emptyArraySegment, disconnectToken).PreserveCultureNotContext();

            if (TryGetMessage(receiveResult, null, out message))
            {
                return message;
            }

            var buffer = new byte[bufferSize];

            // Now read with the real buffer
            var arraySegment = new ArraySegment<byte>(buffer);

            receiveResult = await webSocket.ReceiveAsync(arraySegment, disconnectToken).PreserveCultureNotContext();

            if (TryGetMessage(receiveResult, buffer, out message))
            {
                return message;
            }
            else
            {
                // for multi-fragment messages, we need to coalesce
                ByteBuffer bytebuffer = new ByteBuffer(maxMessageSize);
                bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
                WebSocketMessageType originalMessageType = receiveResult.MessageType;

                while (true)
                {
                    // loop until an error occurs or we see EOF
                    receiveResult = await webSocket.ReceiveAsync(arraySegment, disconnectToken).PreserveCultureNotContext();

                    if (receiveResult.MessageType == WebSocketMessageType.Close)
                    {
                        return WebSocketMessage.CloseMessage;
                    }

                    if (receiveResult.MessageType != originalMessageType)
                    {
                        throw new InvalidOperationException("Incorrect message type");
                    }

                    bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));

                    if (receiveResult.EndOfMessage)
                    {
                        switch (receiveResult.MessageType)
                        {
                            case WebSocketMessageType.Binary:
                                return new WebSocketMessage(bytebuffer.GetByteArray(), WebSocketMessageType.Binary);

                            case WebSocketMessageType.Text:
                                return new WebSocketMessage(bytebuffer.GetString(), WebSocketMessageType.Text);

                            default:
                                throw new InvalidOperationException("Unknown message type");
                        }
                    }
                }
            }
        }
开发者ID:FabianGosebrink,项目名称:ASPNET-Core-Angular2-SignalR-Typescript,代码行数:64,代码来源:WebSocketMessageReader.cs

示例15: CheckHeaders

 // Web sockets start off as minimal HTTP connections, upgrade, and then behave like TCP sockets for the most part.
 // Thus the 'security service' abstraction is used to insulate this listener from direct TCP objects dependence.
 // Somewhat of a cheat, but it is the way it is :-)!
 private async Task CheckHeaders(WebSocket socket) {
     byte[] buffer = new byte[Config.Get(Constants.Configuration.MaxPayloadLength)];
     var response = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.Token);
     // TODO: Ensure complete message is received
     var result = Encoding.ASCII.GetString(buffer, 0, response.Count);
     LogFacade.Instance.LogDebug("Received headers for web socket verification: " + result);
     SecurityService.DissectAndValidateFrame(result);
 }
开发者ID:afgbeveridge,项目名称:Quorum,代码行数:11,代码来源:HttpEventListener.cs


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