群聊,基于netty的websocket

<!--建立一个maven工程,然后导入依赖  -->
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.31.Final</version>
</dependency>
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class webSocketNetty {
    public static void main(String[] args) {
        //创建两个线程池
        NioEventLoopGroup mainGrp = new NioEventLoopGroup();//主线程池
        NioEventLoopGroup subGrp = new NioEventLoopGroup();//从线程池
        try {
            //创建netty服务启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            //初始化服务器启动对象
            serverBootstrap
                    //指定使用上面创建的两个线程池
                    .group(mainGrp,subGrp)
                    //指定netty通道类型
                    .channel(NioServerSocketChannel.class)
                    //指定通道初始化器,用来加载当channel收到事件后如何进行业务处理
                    .childHandler(new WebSocketChannelInitializer());

            //绑定服务器端口,以同步的方式启动服务器
            ChannelFuture future = serverBootstrap.bind(9090).sync();
            //等待服务器关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //优雅的关闭服务器
            mainGrp.shutdownGracefully();
            subGrp.shutdownGracefully();
        }
    }
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 通道初始化器
 * 用来加载通道处理器(channelHandel)
 */
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {
    //初始化通道
    //在这个方法中加载对应的channelHandel
    protected void initChannel(SocketChannel ch) throws Exception {
        //获取管道,将一个个的channelHandel加载到管道中
        ChannelPipeline pipeline = ch.pipeline();

        //添加一个http的编解码器
        pipeline.addLast(new HttpServerCodec());
        //添加一个用于支持大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        //添加一个聚合器,这个聚合器主要是将httpMessage聚合成FullHttpRequest/Response
        pipeline.addLast(new HttpObjectAggregator(1024 * 64));

        //需要指定接收路由的请求
        //必须使用ws后缀结尾的url才能访问
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

        //添加自定义的Handler
        pipeline.addLast(new ChatHandler());

    }
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> /*implements ChannelHandler, EventExecutorGroup*/ {
    //用来保存所有的客户端连接
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    //当channel有新的事件消息,会自动调用这个方法
    protected void channelRead0(ChannelHandlerContext chc, TextWebSocketFrame msg) throws Exception {
        //当接收到数据后会自动调用

        //获取客户端发送过来的消息
        String text = msg.text();
        System.out.println("接受到的消息为:" + text);

        //群发消息
        clients.forEach(x -> {
            x.writeAndFlush(new TextWebSocketFrame(formatter.format(LocalDateTime.now()) + ":" + text));
        });
    }

    //当有新的客户端连接服务器后,会自动调用这个方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //将新的通道加入clients中
        clients.add(ctx.channel());
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" id="msg">
    <input type="button" value="发送消息" onclick="sendMsg()">

    接受到的消息:
    <p id="server_msg" style="background-color: #AAAAAA"></p>

    <script>
    var webSocket = null;
    <!--  判断当前浏览器是否支持web socket      -->
    if(window.WebSocket){
        webSocket = new WebSocket("ws://127.0.0.1:9090/ws");

        webSocket.onopen = function (ev) {
            console.log("简历连接");
        }
        webSocket.onclose = function (ev) {
            console.log("关闭连接");
        }
        webSocket.onmessage = function (ev) {
            console.log("接受到服务器的消息" + ev.data);
            var serverMsg = document.getElementById("server_msg");
            serverMsg.innerHTML += ev.data + "<br/>"
        }
    }else{
        alert("当前浏览器不支持web socket")
    }

    function sendMsg() {
        var message = document.getElementById("msg");
        webSocket.send(message.value);
    }
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值