• websocket入门代码


    实时通信

    • Ajax轮训
      • 异步的每隔一段时间向服务器发送一次请求
    • Long pull
      • 类似Ajax请求,是阻塞的方式,请求服务器端后会一直等待服务器响应
    • websocket
      • 基于HTTP协议的持久化协议
      • WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
      • WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

    服务端实现代码

    public class WSServer {
    
        public static void main(String[] args) throws InterruptedException {
            EventLoopGroup mainGroup = new NioEventLoopGroup();
            EventLoopGroup subGroup = new NioEventLoopGroup();
    
            try {
                ServerBootstrap server = new ServerBootstrap();
                server.group(mainGroup,subGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new WSServerInitializer());
                ChannelFuture channelFuture = server.bind(8080).sync();
                channelFuture.channel().closeFuture().sync();
            } finally {
                mainGroup.shutdownGracefully();
                subGroup.shutdownGracefully();
            }
        }
    }
    
    public class WSServerInitializer extends ChannelInitializer<SocketChannel> {
    
    
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            // websocket基于http协议,所以要有http编解码器
            pipeline.addLast(new HttpServerCodec());
            // 对写大数据流的支持
            pipeline.addLast(new ChunkedWriteHandler());
            // 对httpMessage进行聚合, 聚合成FullHttpRequest或fullHttpResponse
            pipeline.addLast(new HttpObjectAggregator(1024*64));
            // ----------------- 以上用于支持HTTP协议------------------
            // websocket处理的协议,用于指定给客户端连接访问的路由, : /ws
            // 本handler会帮你处理一些繁重的复杂的事
            // 会帮你处理握手动作: handshaking(close,ping,pong) ping+pong=心跳
            // 对于websocket来说,都是以frames进行传输的,不同的数据类型对应的frames也不同
            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
            // 自定义的handler
            pipeline.addLast(new ChatHandler());
        }
    }
    
    /**
     * @author: webin
     * @date: 2020/4/4 15:57
     * @description:    处理消息的handler
     *  TextWebSocketFrame: 在netty中,是用于为websocket专门处理文本的对象,frame是消息的载体
     * @version: 0.0.1
     */
    public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    
        /** 用于置入和管理所有客户端的channel,把所有的channel都保存到组里面去 */
        private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {
            // 获取客户端传输过来的消息
            String text = msg.text();
            System.out.println("接收到的输出: " + text);
    
            for (Channel channel : clients) {
                channel.writeAndFlush(
                        new TextWebSocketFrame("[服务器接收到消息:]"+ LocalDateTime.now()+" 接收到消息,消息内容为: "+text)
                );
            }
            // 和上面作用一样
    //        clients.writeAndFlush(
    //                new TextWebSocketFrame("[服务器接收到消息:]"+ LocalDateTime.now()+" 接收到消息,消息内容为: "+text)
    //        );
    
        }
    
        /**
         *  当客户端连接服务端会后
         *  获取客户端的channel,并且放到channelGroup中进行管理
         * @param ctx
         * @throws Exception
         */
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    
            clients.add(ctx.channel());
        }
    
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
           // 当触发handlerRemoved,ChannelGroup会自动移除对应客户端的Channel
            clients.remove(ctx.channel());
            System.out.println("客户端断开,channel对应的长id:" + ctx.channel().id().asLongText());
            System.out.println("客户端断开,channel对应的短id:" + ctx.channel().id().asShortText());
        }
    }
    

    客户端实现代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>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>
    </body>
    <script>
        window.CHAT = {
            socket: null,
            init: function () {
                if (window.WebSocket) {
                    CHAT.socket = new WebSocket("ws://127.0.0.1:8080/ws");
                    CHAT.socket.onopen = 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
                    };
                    CHAT.socket.close = function() {
                        console.log("连接关闭...")
                    };
                    CHAT.socket.onerror = function () {
                        console.log("发生错误 ... ")
                    }
                } else {
                    alert("浏览器不知道WebSocket协议")
                }
            },
            chat: function () {
                var msg = document.getElementById("msgContent")
                CHAT.socket.send(msg.value)
            }
        }
        CHAT.init();
    </script>
    </html>
    
    
  • 相关阅读:
    数字配对(bzoj 4514)
    任务查询系统(bzoj 3932)
    楼房重建(bzoj 2957)
    Hotel(poj 3667)
    Can you answer these queries(spoj 1043)
    亚瑟王(bzoj 4008)
    潘多拉的盒子(bzoj 1194)
    Circling Round Treasures(codeforces 375c)
    莫队算法---基础知识介绍(转载)
    HDU 1141---Brackets Sequence(区间DP)
  • 原文地址:https://www.cnblogs.com/smallwolf/p/12632924.html
Copyright © 2020-2023  润新知