Netty WebSocket demo code

1 WebSocketServer

@Slf4j
public class WebSocketServer {

    public static void main(String[] args) {

        //创建主从线程池
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(2);
        try {
            //创建服务器类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WSServerInitializer());
            //绑定端口
            ChannelFuture future = serverBootstrap.bind(8088).sync();
            log.info("WebSocketServer starting ...");
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            e.printStackTrace();
        }


    }

}

2 WSServerInitializer

public class WSServerInitializer extends ChannelInitializer<NioSocketChannel> {

    @Override
    protected void initChannel(NioSocketChannel channel) throws Exception {

        //获取管道
        ChannelPipeline pipeline = channel.pipeline();
        //websocket 基于http协议,所需要的http编解码器
        pipeline.addLast(new HttpServerCodec());
        //http上有一些数据流产生,有大有小,需要使用netty对大数据流写提供支持
        pipeline.addLast(new ChunkedWriteHandler());
        //http 请求、响应聚和处理  64kb
        pipeline.addLast(new HttpObjectAggregator(1024 * 64));
        //添加websocket路由
        //websocket都是以frams进行传输的
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        //自定义handler
        pipeline.addLast(new CustomerHandler());

    }
}

3 CustomerHandler

/**
 * 用于处理消息的handler
 * 由于它的传输数据载体是frame,这个frame在netty,是用于为websocket专门处理文本对象的,frame是消息载体
 */
@Slf4j
public class CustomerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    public CustomerHandler() {
        log.info("CustomerHandler invoke CustomerHandler");
    }


    /**
     * 用于记录和管理所有客户端的channel
     */
    private ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //获取客户端所传输的消息
        String text = msg.text();
        log.info("接收到的数据:{}", text);

        String responseMessage = "服务端接收到消息:" + text;

        //将数据刷新到客户端上
        clients.writeAndFlush(new TextWebSocketFrame(responseMessage));
    }


    /**
     * 拦截器 起
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }


    /**
     * 拦截器终
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        clients.remove(ctx.channel());
        log.info("客户端:{} 已经断开", ctx.channel().id().asLongText());
    }
}

4 index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Netty 实时通信</title>
	</head>
	<body>
		发送消息:<input type="text" id="msgContent" />
		<input type="button" value="发送消息" onclick="CHAT.chat()" />
		<hr />
		接收消息:
		<div id="receiveMsg"></div>
		
		<script type="text/javascript">
			window.CHAT = {
				socket: null,
				init:function(){
					//判断浏览器是否支持websocket
					if(window.WebSocket){
						//创建websocket 对象
						CHAT.socket = new WebSocket("ws://127.0.0.1:8088/ws");
						CHAT.socket.onopen = function(){
							console.log("链接建立成功");
						},
						CHAT.socket.close=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{
						console.log("您的浏览器不支持websocket协议");
					}
				},
				chat:function(){
					//获取发送消息框中所输入内容
					var msgContent = document.getElementById("msgContent").value;
					//将客户输入的消息进行发送
					CHAT.socket.send(msgContent);
				}
			};
			CHAT.init();
		</script>
	</body>
</html>

5 运行

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

响彻天堂丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值