public void TestNeverSkip() { IWebSocketExtensionFilter neverSkip = NeverSkipWebSocketExtensionFilter.Instance; BinaryWebSocketFrame binaryFrame = new BinaryWebSocketFrame(); Assert.False(neverSkip.MustSkip(binaryFrame)); Assert.True(binaryFrame.Release()); TextWebSocketFrame textFrame = new TextWebSocketFrame(); Assert.False(neverSkip.MustSkip(textFrame)); Assert.True(textFrame.Release()); PingWebSocketFrame pingFrame = new PingWebSocketFrame(); Assert.False(neverSkip.MustSkip(pingFrame)); Assert.True(pingFrame.Release()); PongWebSocketFrame pongFrame = new PongWebSocketFrame(); Assert.False(neverSkip.MustSkip(pongFrame)); Assert.True(pongFrame.Release()); CloseWebSocketFrame closeFrame = new CloseWebSocketFrame(); Assert.False(neverSkip.MustSkip(closeFrame)); Assert.True(closeFrame.Release()); ContinuationWebSocketFrame continuationFrame = new ContinuationWebSocketFrame(); Assert.False(neverSkip.MustSkip(continuationFrame)); Assert.True(continuationFrame.Release()); }
static void Main(string[] args) { var client = DotNettyServiceProvider.Current.GetRequiredService <IWebSocketClient>(); client.StartAsync(async channel => { while (true) { string msg = Console.ReadLine(); if (msg.IsNull()) { break; } else if ("bye".Equals(msg, StringComparison.OrdinalIgnoreCase)) { await channel.WriteAndFlushAsync(new CloseWebSocketFrame()); break; } else if ("ping".Equals(msg, StringComparison.OrdinalIgnoreCase)) { var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 })); await channel.WriteAndFlushAsync(frame); } else { var frame = new TextWebSocketFrame(msg); await channel.WriteAndFlushAsync(frame); } } await channel.CloseAsync(); }) .Wait(); }
/// <summary> /// 开启ping保持连接 /// </summary> public void StartPing() { pingWork.Start("sendPing", () => { var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 })); channel.WriteAndFlushAsync(frame); //Console.WriteLine("sendPing"); return(true); }, 3); }
public override void UserEventTriggered(IChannelHandlerContext context, object evt) { if (evt is IdleStateEvent stateEvent) { s_logger.LogWarning($"{nameof(WebSocketClientHandler)} caught idle state: {stateEvent.State}"); var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 })); context.Channel.WriteAndFlushAsync(frame); } else if (evt is WebSocketClientProtocolHandler.ClientHandshakeStateEvent handshakeStateEvt && handshakeStateEvt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HandshakeComplete) { _handshakeFuture.TryComplete(); } }
public void PingFrame() { IByteBuffer pingData = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes("Hello, world")); var channel = new EmbeddedChannel(new Handler()); var inputMessage = new PingWebSocketFrame(pingData); Assert.False(channel.WriteInbound(inputMessage)); // the message was not propagated inbound // a Pong frame was written to the channel var response = channel.ReadOutbound <PongWebSocketFrame>(); Assert.Equal(pingData, response.Content); pingData.Release(); Assert.False(channel.Finish()); }
static async Task RunClientAsync() { var builder = new UriBuilder { Scheme = "ws", Host = "127.0.0.1", Port = 18089 }; string path = "websocket"; if (!string.IsNullOrEmpty(path)) { builder.Path = path; } Uri uri = builder.Uri; //ExampleHelper.SetConsoleLogger(); IEventLoopGroup group = new MultithreadEventLoopGroup(); try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true); bootstrap.Channel <TcpSocketChannel>(); // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. var handShaker = WebSocketClientHandshakerFactory.NewHandshaker( uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()); var channelGroup = new DefaultChannelGroup(null); bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast( new HttpClientCodec(), new HttpObjectAggregator(8192), //WebSocketClientCompressionHandler.Instance, new WebSocketClientProtocolHandler(handShaker, true), new BinaryWebSocketFrameHandler(), new ProtocolDecoder(), new ProtocolEncoder(), new MessageHandler(channelGroup)); pipeline.AddLast(new ProtocolEncoder()); })); IChannel ch = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 18089)); Console.WriteLine("WebSocket handshake completed.\n"); Console.WriteLine("\t[bye]:Quit \n\t [ping]:Send ping frame\n\t Enter any text and Enter: Send text frame"); while (true) { string msg = Console.ReadLine(); if (msg == null) { break; } else if ("bye".Equals(msg.ToLower())) { await ch.WriteAndFlushAsync(new CloseWebSocketFrame()); break; } else if ("ping".Equals(msg.ToLower())) { var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 })); await ch.WriteAndFlushAsync(frame); } else { //WebSocketFrame frame = new TextWebSocketFrame(msg); //await ch.WriteAndFlushAsync(frame); var req = new LoginValidateRequest { Account = "sp001", Passwd = "111", ZoneId = 4 }; await ch.WriteAndFlushAsync(req); } } await ch.CloseAsync(); } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
static async Task Main(string[] args) { var builder = new UriBuilder { Scheme = ClientSettings.IsSsl ? "wss" : "ws", Host = ClientSettings.Host.ToString(), Port = ClientSettings.Port, }; string path = ExampleHelper.Configuration["path"]; builder.Path = !string.IsNullOrEmpty(path) ? path : WEBSOCKET_PATH; Uri uri = builder.Uri; ExampleHelper.SetConsoleLogger(); bool useLibuv = ClientSettings.UseLibuv; Console.WriteLine("Transport type : " + (useLibuv ? "Libuv" : "Socket")); IEventLoopGroup group; if (useLibuv) { group = new EventLoopGroup(); } else { group = new MultithreadEventLoopGroup(); } X509Certificate2 cert = null; string targetHost = null; if (ClientSettings.IsSsl) { cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password"); targetHost = cert.GetNameInfo(X509NameType.DnsName, false); } try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true); if (useLibuv) { bootstrap.Channel <TcpChannel>(); } else { bootstrap.Channel <TcpSocketChannel>(); } // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. WebSocketClientHandler handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.NewHandshaker( uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders())); bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (cert != null) { pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); } pipeline.AddLast("idleStateHandler", new IdleStateHandler(0, 0, 60)); pipeline.AddLast(new LoggingHandler("CONN")); pipeline.AddLast( new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.Instance, //new WebSocketClientProtocolHandler( // webSocketUrl: uri, // version: WebSocketVersion.V13, // subprotocol: null, // allowExtensions: true, // customHeaders: new DefaultHttpHeaders(), // maxFramePayloadLength: 65536, // handleCloseFrames: true, // performMasking: false, // allowMaskMismatch: true, // enableUtf8Validator: false), new WebSocketFrameAggregator(65536), handler); })); try { IChannel ch = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port)); await handler.HandshakeCompletion; Console.WriteLine("WebSocket handshake completed.\n"); Console.WriteLine("\t[bye]:Quit \n\t [ping]:Send ping frame\n\t Enter any text and Enter: Send text frame"); while (true) { string msg = Console.ReadLine(); if (msg == null) { break; } msg = msg.ToLowerInvariant(); switch (msg) { case "bye": await ch.WriteAndFlushAsync(new CloseWebSocketFrame()); goto CloseLable; case "ping": var ping = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 })); await ch.WriteAndFlushAsync(ping); break; case "this is a test": await ch.WriteAndFlushManyAsync( new TextWebSocketFrame(false, "this "), new ContinuationWebSocketFrame(false, "is "), new ContinuationWebSocketFrame(false, "a "), new ContinuationWebSocketFrame(true, "test") ); break; case "this is a error": await ch.WriteAndFlushAsync(new TextWebSocketFrame(false, "this ")); await ch.WriteAndFlushAsync(new ContinuationWebSocketFrame(false, "is ")); await ch.WriteAndFlushAsync(new ContinuationWebSocketFrame(false, "a ")); await ch.WriteAndFlushAsync(new TextWebSocketFrame(true, "error")); break; default: await ch.WriteAndFlushAsync(new TextWebSocketFrame(msg)); break; } } CloseLable: await ch.CloseAsync(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.WriteLine("按任意键退出"); Console.ReadKey(); } } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }
static async Task RunClientAsync() { var builder = new UriBuilder { Scheme = ClientSettings.IsSsl ? "wss" : "ws", Host = ClientSettings.Host.ToString(), Port = ClientSettings.Port }; string path = ExampleHelper.Configuration["path"]; if (!string.IsNullOrEmpty(path)) { builder.Path = path; } Uri uri = builder.Uri; ExampleHelper.SetConsoleLogger(); bool useLibuv = ClientSettings.UseLibuv; Console.WriteLine("Transport type : " + (useLibuv ? "Libuv" : "Socket")); IEventLoopGroup group; if (useLibuv) { group = new EventLoopGroup(); } else { group = new MultithreadEventLoopGroup(); } X509Certificate2 cert = null; string targetHost = null; if (ClientSettings.IsSsl) { cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password"); targetHost = cert.GetNameInfo(X509NameType.DnsName, false); } try { var bootstrap = new Bootstrap(); bootstrap .Group(group) .Option(ChannelOption.TcpNodelay, true); if (useLibuv) { bootstrap.Channel <TcpChannel>(); } else { bootstrap.Channel <TcpSocketChannel>(); } // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. var handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.NewHandshaker( uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders())); bootstrap.Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (cert != null) { pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); } pipeline.AddLast( new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.Instance, handler); })); IChannel ch = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port)); await handler.HandshakeCompletion; Console.WriteLine("WebSocket handshake completed.\n"); Console.WriteLine("\t[bye]:Quit \n\t [ping]:Send ping frame\n\t Enter any text and Enter: Send text frame"); while (true) { string msg = Console.ReadLine(); if (msg == null) { break; } else if ("bye".Equals(msg.ToLower())) { await ch.WriteAndFlushAsync(new CloseWebSocketFrame()); break; } else if ("ping".Equals(msg.ToLower())) { var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 })); await ch.WriteAndFlushAsync(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); await ch.WriteAndFlushAsync(frame); } } await ch.CloseAsync(); } finally { await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); } }