zoukankan      html  css  js  c++  java
  • 【Netty】(7)---搭建websocket服务器

    【Netty】(7)---搭建websocket服务器

    说明:本篇博客是基于学习某网有关视频教学。
    目的:创建一个websocket服务器,获取客户端传来的数据,同时向客户端发送数据

    一、服务端

    1、Main主类

    public class WSServer {
        public static void main(String[] args) throws Exception {
    
            // 定义一对线程组
            // 主线程组, 用于接受客户端的连接,
            EventLoopGroup mainGroup = new NioEventLoopGroup();
            // 从线程组, 负责IO交互工作
            EventLoopGroup subGroup = new NioEventLoopGroup();
            try {
                //netty服务器的创建, 辅助工具类,用于服务器通道的一系列配置
                ServerBootstrap server = new ServerBootstrap();
                //绑定两个线程组
                server.group(mainGroup, subGroup)
                        //指定NIO的模式
                        .channel(NioServerSocketChannel.class)
                        //子处理器,用于处理workerGroup
                        .childHandler(new WSServerInitialzer());
    
                // 启动server,并且设置8088为启动的端口号,同时启动方式为同步
                ChannelFuture future = server.bind(8088).sync();
                // 监听关闭的channel,设置位同步方式
                future.channel().closeFuture().sync();
            } finally {
                //退出线程组
                mainGroup.shutdownGracefully();
                subGroup.shutdownGracefully();
            }
        }
    }
    

    2、WSServerInitialzer类(子处理器)

    public class WSServerInitialzer extends ChannelInitializer<SocketChannel> {
    
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
    
            // websocket 基于http协议,所以要有http编解码器 服务端用HttpServerCodec
            pipeline.addLast(new HttpServerCodec());
            // 对写大数据流的支持
            pipeline.addLast(new ChunkedWriteHandler());
    
          /**
             * 我们通常接收到的是一个http片段,如果要想完整接受一次请求的所有数据,我们需要绑定HttpObjectAggregator,然后我们
             * 就可以收到一个FullHttpRequest-是一个完整的请求信息。
             *对httpMessage进行聚合,聚合成FullHttpRequest或FullHttpResponse
             * 几乎在netty中的编程,都会使用到此hanler
             */
            pipeline.addLast(new HttpObjectAggregator(1024*64));
    
            // ====================== 以上是用于支持http协议 , 以下是支持httpWebsocket   ======================
    
            /**
             * websocket 服务器处理的协议,用于指定给客户端连接访问的路由 : /ws
             * 本handler会帮你处理一些繁重的复杂的事
             * 会帮你处理握手动作: handshaking(close, ping, pong) ping + pong = 心跳
             * 对于websocket来讲,都是以frames进行传输的,不同的数据类型对应的frames也不同
             */
            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
    
            // 自定义的handler
            pipeline.addLast(new ChatHandler());
        }
    
    }
    

    3、ChatHandler(助手类)

    /**
     * @Description: 处理消息的handler
     * TextWebSocketFrame: 在netty中,是用于为websocket专门处理文本的对象,frame是消息的载体
     *  这里已经指定了类型 如果这里是Object 那么下面还需判断是不是TextWebSocketFrame类型
     */
    public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    
        // 用于记录和管理所有客户端的channle
        private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg)
                throws Exception {
            // 获取客户端传输过来的消息
            String content = msg.text();
            System.out.println("接受到的数据:" + content);
    
    //    	for (Channel channel: clients) {
    //			channel.writeAndFlush(
    //				new TextWebSocketFrame(
    //						"[服务器在]" + LocalDateTime.now()
    //						+ "接受到消息, 消息为:" + content));
    //		}
            // 下面这个方法,和上面的for循环,一致   向客户端发送数据
            clients.writeAndFlush(new TextWebSocketFrame("我是服务器,我收到你的消息为:" + content));
    
        }
    
        /**
         * 当客户端连接服务端之后(打开连接)
         * 获取客户端的channle,并且放到ChannelGroup中去进行管理
         */
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            clients.add(ctx.channel());
        }
    
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            // 当触发handlerRemoved,ChannelGroup会自动移除对应客户端的channel,所以下面的remove不用我们再手写
    //		clients.remove(ctx.channel());
            System.out.println("客户端断开,channle对应的长id为:" + ctx.channel().id().asLongText());
            System.out.println("客户端断开,channle对应的短id为:" + ctx.channel().id().asShortText());
        }
    }
    

    到这里服务端已经写好了,和之前搭建的服务器大致没什么区别,主要区别在于ChannelPipeline添加了不同的Handel,助手类对websocket做了些处理工作。


    二、客户端

    客户端这边是采用Hbuilderx工具创建的前端项目,代码如下

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8" />
    		<title></title>
    	</head>
    	<body>
    		
    		<div>发送消息:</div>
    		<input type="text" id="msgContent"/>
    		<input type="button" value="点我发送" onclick="CHAT.chat()"/>
    		
    		<div>接受消息:</div>
    		<div id="receiveMsg" style="background-color: gainsboro;"></div>
    		
    		<script type="application/javascript">
    			
    			window.CHAT = {
    				socket: null,
    				init: function() {
    					<!--判断浏览器是否支持 websocket-->
    					if (window.WebSocket) {
    						<!--连接服务器websocket IP+端口号 /ws是服务器WebSocketServerProtocolHandler添加的-->
    						CHAT.socket = new WebSocket("ws://127.0.0.1:8088/ws");
    						CHAT.socket.onopen = function() {
    							console.log("连接建立成功...");
    						},
    						CHAT.socket.onclose = function() {
    							console.log("连接关闭...");
    						},
    						CHAT.socket.onerror = function() {
    							console.log("发生错误...");
    						},
    						CHAT.socket.onmessage = function(e) {
    							console.log("接受到消息:" + e.data);
    							var receiveMsg = document.getElementById("receiveMsg");
    							var html = receiveMsg.innerHTML;
    							receiveMsg.innerHTML = html + "<br/>" + e.data;
    						}
    					} else {
    						alert("浏览器不支持websocket协议...");
    					}
    				},
    				<!--onclick事件触发-->
    				chat: function() {
    					
    					<!--获取消息,发送消息-->
    					var msg = document.getElementById("msgContent");
    					CHAT.socket.send(msg.value);
    				}
    			};
    			
    			<!--初始化方法-->
    			CHAT.init();
    			
    		</script>
    	</body>
    </html>
    
    

    三、测试

    通过测试可以总结

    1、页面初始化的时候就已经成功和服务端websocket建立连接成功。
    2、服务端收到客户端数据,并向客户端发送数据。
    3、当关闭页面的时候,既相当于关闭了该websocket连接,服务端会自动移除。
    
  • 相关阅读:
    11 MySQL视图
    10 MySQL索引选择与使用
    08 MySQL存储引擎
    09 MySQL字符集
    06 MySQL运算符
    07 MySQL常用内置函数
    05 MySQL数据类型的选择与使用
    04 MySQL数据类型
    js 当前日期后7天
    md5加密
  • 原文地址:https://www.cnblogs.com/qdhxhz/p/10145083.html
Copyright © 2011-2022 走看看