static async Task RunWebSocketServer() { HttpListenerContext context = await listener.GetContextAsync(); if (!context.Request.IsWebSocketRequest) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.Close(); } HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(WebSocketConstants.SubProtocols.Mqtt, 8 * 1024, TimeSpan.FromMinutes(5)); serverListener = new ReadListeningHandler(); serverWebSocketChannel = new ServerWebSocketChannel(null, webSocketContext.WebSocket, context.Request.RemoteEndPoint); serverWebSocketChannel .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default) .Option(ChannelOption.AutoRead, true) .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator()) .Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default); serverWebSocketChannel.Pipeline.AddLast("server logger", new LoggingHandler("SERVER")); serverWebSocketChannel.Pipeline.AddLast( MqttEncoder.Instance, new MqttDecoder(true, 256 * 1024), serverListener); var workerGroup = new MultithreadEventLoopGroup(); await workerGroup.GetNext().RegisterAsync(serverWebSocketChannel); while (true) { if (done) { break; } await Task.Delay(TimeSpan.FromSeconds(2)); } }
public async Task MqttWebSocketClientAndServerScenario() { var websocket = new ClientWebSocket(); websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Mqtt); Uri uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix); await websocket.ConnectAsync(uri, CancellationToken.None); var clientReadListener = new ReadListeningHandler(); var clientChannel = new ClientWebSocketChannel(null, websocket); clientChannel .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default) .Option(ChannelOption.AutoRead, true) .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator()) .Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default); clientChannel.Pipeline.AddLast( MqttEncoder.Instance, new MqttDecoder(false, 256 * 1024), clientReadListener); var clientWorkerGroup = new MultithreadEventLoopGroup(); await clientWorkerGroup.GetNext().RegisterAsync(clientChannel); await Task.WhenAll(RunMqttClientScenarioAsync(clientChannel, clientReadListener), RunMqttServerScenarioAsync(serverWebSocketChannel, serverListener)); done = true; }