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


C# WebSockets.WebSocket类代码示例

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


WebSocket类属于System.Net.WebSockets命名空间,在下文中一共展示了WebSocket类的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: 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

示例3: DashboardSocketHandler

 public DashboardSocketHandler(WebSocket socket)
 {
     Socket = socket;
     MasterController.Instance.Listener.Status.Updated += ListenerStatusUpdated;
     MasterController.Instance.Transmitter.Status.Updated += TransmitterStatusUpdated;
     Venue.Status.Updated += Status_Updated;
 }
开发者ID:iKadmium,项目名称:kadmium-osc-dmx-dotnet,代码行数:7,代码来源:DashboardSocketHandler.cs

示例4: TestChatHanlder_OnReceive

 private void TestChatHanlder_OnReceive(WebSocket Socket, WebSocketMessageType Type, byte[] ReceiveMessage)
 {
     //並行廣播給所有使用者,也可以轉發給指定使用者
     Parallel.ForEach(WebSocketList, async socket => {
         await socket.SendAsync(new ArraySegment<byte>(ReceiveMessage), Type, true, CancellationToken.None);
     });
 }
开发者ID:XuPeiYao,项目名称:AspNetCoreTemplate,代码行数:7,代码来源:TestChatHanlder.cs

示例5: SocketServer

 public SocketServer()
 {
     var websocket = new WebSocket();
     _tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 56837);//8095
     _dictionary = new ConcurrentDictionary<string, SocketWrapper>();
     _connections = new List<SocketWrapper>();
 }
开发者ID:Sharpiro,项目名称:Websockets.Template,代码行数:7,代码来源:SocketServer.cs

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

示例7: SACNTransmitterLive

 public SACNTransmitterLive(WebSocket socket)
 {
     Socket = socket;
     var Transmitter = MasterController.Instance.Transmitter as SACNTransmitter;
     UniverseID = 1;
     Transmitter.OnTransmit += Transmitter_OnTransmit;
 }
开发者ID:iKadmium,项目名称:kadmium-osc-dmx-dotnet,代码行数:7,代码来源:SACNTransmitterLive.cs

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

示例9: SendMessage

        private static async Task SendMessage(WebSocket webSocket, string msg, bool endOfMessage)
        {
            logger.LogVerbose("SendMessage = {0}", msg);

            var msgBytes = Encoding.UTF8.GetBytes(msg);
            await webSocket.SendAsync(new ArraySegment<byte>(msgBytes, 0, msgBytes.Length), WebSocketMessageType.Text, endOfMessage, CancellationToken.None);
        }
开发者ID:streamcode9,项目名称:chat,代码行数:7,代码来源:WebSocketsHelper.cs

示例10: Connection

 public Connection(HttpContext context, WebSocket socket)
 {
     Id = Guid.NewGuid();
     Context = context;
     Socket = socket;
     AccessLevel = AccessLevel.Guest;
 }
开发者ID:McBits,项目名称:DungeonR,代码行数:7,代码来源:Connection.cs

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

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

示例13: ConnectAsync

        internal async Task<IAsyncTransport> ConnectAsync(Address address, Action<ClientWebSocketOptions> options)
        {
            Uri uri = new UriBuilder()
            {
                Scheme = address.Scheme,
                Port = GetDefaultPort(address.Scheme, address.Port),
                Host = address.Host,
                Path = address.Path
            }.Uri;

            ClientWebSocket cws = new ClientWebSocket();
            cws.Options.AddSubProtocol(WebSocketSubProtocol);
            if (options != null)
            {
                options(cws.Options);
            }

            await cws.ConnectAsync(uri, CancellationToken.None);
            if (cws.SubProtocol != WebSocketSubProtocol)
            {
                cws.Abort();

                throw new NotSupportedException(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "WebSocket SubProtocol used by the host is not the same that was requested: {0}",
                        cws.SubProtocol ?? "<null>"));
            }

            this.webSocket = cws;

            return this;
        }
开发者ID:Azure,项目名称:amqpnetlite,代码行数:33,代码来源:WebSocketTransport.cs

示例14: WebsocketSendAsync

 public WebsocketSendAsync(WebSocket webSocket, CompletionQueue completion_queue)
 {
     if (null == webSocket) throw new ArgumentException();
     this.webSocket = webSocket;
     if (null == completion_queue) throw new ArgumentException();
     this.completion_queue = completion_queue;
 }
开发者ID:unicomp21,项目名称:Node.cs,代码行数:7,代码来源:WebsocketSendAsync.cs

示例15: ProcessRequestAsync

        public override async Task ProcessRequestAsync(HttpContext httpContext)
        {
            await Task.Run(() =>
            {
                if (httpContext.IsWebSocketRequest)
                {
                    httpContext.AcceptWebSocketRequest(async delegate(AspNetWebSocketContext context)
                    {
                        this.Socket = context.WebSocket;

                        while (this.Socket != null || this.Socket.State != WebSocketState.Closed)
                        {
                            ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
                            WebSocketReceiveResult receiveResult = await this.Socket.ReceiveAsync(buffer, CancellationToken.None);

                            try
                            {
                                switch (receiveResult.MessageType)
                                {
                                    case WebSocketMessageType.Text:
                                        string message = Encoding.UTF8.GetString(buffer.Array, 0, receiveResult.Count);
                                        this.OnMessageReceived(message);
                                        break;
                                    case WebSocketMessageType.Binary:
                                        this.OnMessageReceived(buffer.Array);
                                        break;
                                    case WebSocketMessageType.Close:
                                        this.OnClosing(true, receiveResult.CloseStatusDescription);
                                        break;
                                }

                                switch (this.Socket.State)
                                {
                                    case WebSocketState.Connecting:
                                        this.OnConnecting();
                                        break;
                                    case WebSocketState.Open:
                                        this.OnOpen();
                                        break;
                                    case WebSocketState.CloseSent:
                                        this.OnClosing(false, string.Empty);
                                        break;
                                    case WebSocketState.CloseReceived:
                                        this.OnClosing(true, string.Empty);
                                        break;
                                    case WebSocketState.Closed:
                                        this.OnClosed();
                                        break;
                                }
                            }
                            catch (Exception ex)
                            {
                                this.OnError(ex);
                            }
                        }
                    });
                }
            });
        }
开发者ID:ehoog,项目名称:StockTickerDemo,代码行数:59,代码来源:WebSocketAsyncHandler.cs


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