netty搭建web聊天室(2)群聊

上节课完成了netty的后端搭建,搞定了简单的http请求响应,今天来结合前端websocket来完成群聊功能。话不多说先上图:

前端构建

  • 不使用复杂构建工具直接静态页面走起

使用了zui样式库 http://zui.sexy/?#/,非常不错,有好多模板。我使用的是聊天模板改造

    
    
  • 主体部分

mike多人聊天室,等你来聊

其他人
其他人的聊天内容
我说话的内容
  • 引入依赖js
    
    
    
    
  • websocket的js代码以及业务代码
  

都有注释就不解释了自己看

后端服务改造

  • ChatHandler改造,判断websocket响应
    /**
     * 读取客户端发送的消息,并将信息转发给其他客户端的 Channel。
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object  request) throws Exception {
           if (request instanceof FullHttpRequest) { //是http请求
               FullHttpResponse response = new DefaultFullHttpResponse(
                        HttpVersion.HTTP_1_1,HttpResponseStatus.OK , Unpooled.wrappedBuffer("Hello netty"
                                .getBytes()));
                response.headers().set("Content-Type", "text/plain");
                response.headers().set("Content-Length", response.content().readableBytes());
                response.headers().set("connection", HttpHeaderValues.KEEP_ALIVE);
                ctx.channel().writeAndFlush(response);
           } else if (request instanceof TextWebSocketFrame) { // websocket请求
               String userId = ctx.channel().id().asLongText();
               System.out.println("收到客户端"+userId+":"+((TextWebSocketFrame)request).text());
               //发送消息给所有客户端
               channels.writeAndFlush(new TextWebSocketFrame(((TextWebSocketFrame)request).text()));
               //发送给单个客户端
               //ctx.channel().writeAndFlush(new TextWebSocketFrame(((TextWebSocketFrame)request).text()));
           }
    }

* ChatServerInitializer改造,加入WebSocket

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
          //websocket协议本身是基于http协议的,所以这边也要使用http解编码器
            pipeline.addLast(new HttpServerCodec());
            //以块的方式来写的处理器
            pipeline.addLast(new ChunkedWriteHandler());
            //netty是基于分段请求的,HttpObjectAggregator的作用是将请求分段再聚合,参数是聚合字节的最大长度
            pipeline.addLast(new HttpObjectAggregator(1024*1024*1024));

            //ws://server:port/context_path
            //ws://localhost:9999/ws
            //参数指的是contex_path
            pipeline.addLast(new WebSocketServerProtocolHandler("/ws",null,true,65535));

            //自定义handler
            pipeline.addLast(new ChatHandler());

            System.out.println("ChatClient:"+ch.remoteAddress() +"连接上");
        
    }

改造完成

启动后端服务,访问你的前端静态页面就可以和小伙伴聊天了。其实后端群聊很简单,就是把一个用户的输入消息,返回给所有在线客户端,前端去负责筛选显示。自己动手照着搞10分钟就能完成。

实现功能

  • 输入聊天昵称开始聊天
  • 聊天消息不为空才能发送
  • 发送完自动清空输入,且聚焦输入框
  • 自己的消息显示在左侧,其他人的消息在右侧

别忘了关注我 mike啥都想搞

求关注啊。

你可能感兴趣的:(netty,websocket,java)