This essay is temporarily not speak principle, first erected a simple Demo communication can be achieved. After a series of essays will be shared on some of the principles.
But before that we had better look at several Netty's threading model, it will have an understanding of the overall logic.
Netty rely introduced in pom.xml after the first project created
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> </dependency>
By Netty need three things to build a WebSocket server as a whole, whether or not SpringBoot framework used, these three things are essential.
1. Start the server class (NettyServer), will conduct some initial configuration.
2. helper class (Handler), have their own definition of helper classes, there are some basic helper classes provided by Netty, such as for Http, WebSocket support of helper classes.
3. initializer (Initializer), we use the following master-slave model thread, the thread from the group will be assigned a different channel to handle different client requests, and each channel there will be a variety of helper classes to implement some of the features . Initializer role is to bind to a variety of helper class.
Server startup class:
public class NettyServer { Private static int Port; public NettyServer ( int Port) { the this .port = Port; } public static void Start () throws InterruptedException {// This method is called in the main method, and set the port number constructor // creating the main thread group, receiving a request EventLoopGroup bossGroup = new new NioEventLoopGroup (); // create from a thread group, the main thread group assignment process down operation io EventLoopGroup workerGroup = new new NioEventLoopGroup (); // Create netty server try { ServerBootstrap of ServerBootstrap = new new of ServerBootstrap (); serverBootstrap.group (bossGroup, workerGroup) // set from the main thread group .Channel (NioServerSocketChannel. Class ) // set nio bidirectional channel .childHandler ( new new NettyServerInitializer ()); // the sub-processing It is used in the processing operation workerGroup // start Server ChannelFuture ChannelFuture = serverBootstrap.bind (Port) .sync (); // monitor off Channel channelFuture.channel () closeFuture () Sync ();.. } the finally { bossGroup.shutdownGracefully (); // Close the main thread workerGroup.shutdownGracefully (); // Close the thread } } }
Initializer:
public class NettyServerInitializer the extends ChannelInitializer <the SocketChannel> { @Override protected void initChannel (the SocketChannel SocketChannel) throws Exception { the ChannelPipeline Pipeline = socketChannel.pipeline (); // The following are three support of Http // HTTP decoder pipeline.addLast ( new new HttpServerCodec ()); // support write large data stream pipeline.addLast ( new new ChunkedWriteHandler ()); // HTTP polymerizer pipeline.addLast ( new newHttpObjectAggregator (* 62 is 1024 )); // WebSocket support provided routing pipeline.addLast ( new new WebSocketServerProtocolHandler ( "/ WS" )); // add custom helper class pipeline.addLast ( new new NettyHandler ()); } }
Custom helper classes:
This class is the core of the request, the client's business will be processed here. Such as the client connection, the client sends a message, and so sends a message to the client.
Custom method helper classes may need to be rewritten according to their needs rewriting, not here to rewrite each method, and we can go to find complete documentation see.
If you need to use the helper class @Autowire annotations can refer to this blog, there are many online instructions, will not repeat it here https://blog.csdn.net/weixin_30828379/article/details/95009595
public class NettyHandler the extends SimpleChannelInboundHandler <TextWebSocketFrame> { // TextWebSocketFrame netty is sent for processing text object websocket // all clients are being connected to the channel exists there, it may be indirectly represented online public static ChannelGroup ChannelGroup = new new DefaultChannelGroup (GlobalEventExecutor.INSTANCE); // number of online public static int online; // receiving the message sent by the client are @Override public void channelRead0 (ChannelHandlerContext CTX, TextWebSocketFrame MSG) throws Exception { SendAllMessages (CTX, send_message);// send_message custom type I, separating the front and rear end often requires a unified data format, the object can be transferred into the first string json then sent to the client } // clients to connect @Override public void handlerAdded (ChannelHandlerContext CTX) throws {Exception channelGroup.add (ctx.channel ()); Online = channelGroup.size (); (. ctx.channel () of the remoteAddress () System.out.println "! on line" + ); } // close the connection ! override public void handlerRemoved (ChannelHandlerContext CTX) throws Exception { channelGroup.remove (ctx.channel ()); Online= ChannelGroup.size (); System.out.println (ctx.channel () of the remoteAddress (). + "Disconnected" ); } // abnormal @Override public void exceptionCaught (CTX ChannelHandlerContext, the cause is the Throwable) throws Exception { cause.printStackTrace (); } // send a message to someone Private void the SendMessage (ChannelHandlerContext CTX, Send_Message MSG) { ctx.channel () writeAndFlush (. new new TextWebSocketFrame (JSON.toJSONString (MSG))); } // for each send personal messages, in addition to message people Private void SendAllMessages(ChannelHandlerContext ctx,Send_Message msg) { for(Channel channel:channelGroup){ if(!channel.id().asLongText().equals(ctx.channel().id().asLongText())){ channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(msg))); } } } }
WebSocket object is to create a front-end access
Api can use some of the message transmitted by the socket, the message receiving operation. Then the received data according to their needs show out on the line, the front end portion will not repeat.
Remember to set the port below 8088 inside the main method.
IF (window.WebSocket) { var Host = window.location.hostname; var URL = "WS: //" + + Host ": 8088 / WS" ; var Socket = new new a WebSocket (URL); } the else { Alert ( " your browser does not support WebSocket Do not use the low version of the IE browser. ". ); }