SpringBoot集成Netty自定义WebSocket服务器实现网页版微信

2 篇文章 0 订阅
1 篇文章 0 订阅

一、前言

前面的文章《SpringBoot集成WebSocket实现简易版微信》已经介绍了通过 SpringBoot 直接集成 WebSocket 的方式来实现一个简易的 Web 版的聊天工具。本文将介绍通过 SpringBoot 集成 Netty 的方式,自定义一个 WebSocket 服务器,并实现与前文中第一版同样的功能。

二、集成步骤

2.1 引入依赖

<!-- 集成Netty -->
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.36.Final</version>
</dependency>

2.2 自定义WebSocket服务

package com.szh.wechat.ws;

import com.szh.wechat.ws.handler.MyWebSocketHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
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;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyWebSocketServer {

    private final int port;

    public MyWebSocketServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        log.info("Starting NettyServer at port: {}", port);
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG, 1024);
            sb.group(group, bossGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class) // 指定使用的channel
                    .localAddress(this.port)// 绑定监听端口
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            log.info("收到新连接");
                            //websocket协议本身是基于http协议的,所以这边也要使用http解编码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            //以块的方式来写的处理器
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/test", "WebSocket", true, 65536 * 10));
                            ch.pipeline().addLast(new MyWebSocketHandler());//自定义助手类
                        }
                    });
            ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
            log.info(MyWebSocketServer.class + " 启动正在监听: " + cf.channel().localAddress());
            cf.channel().closeFuture().sync(); // 关闭服务器通道
        } finally {
            group.shutdownGracefully().sync(); // 释放线程池资源
            bossGroup.shutdownGracefully().sync();
        }
    }
}

2.3 自定义消息处理器

package com.szh.wechat.ws.handler;

import com.alibaba.fastjson.JSONObject;
import com.szh.wechat.common.WeChatConstance.MsgKey;
import com.szh.wechat.common.WeChatConstance.MsgState;
import com.szh.wechat.common.WeChatConstance.MsgType;
import com.szh.wechat.ws.MyChannelHandlerPool;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端建立连接,通道开启!");
        // 添加到channelGroup通道组
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端断开连接,通道关闭!");
        // 从channelGroup通道组移除
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("服务器收到客户端数据:{}", msg.text());
        String msgText = msg.text();
        JSONObject jsonObject = JSONObject.parseObject(msgText);
        if (MsgType.REGISTER.equals(jsonObject.getString(MsgKey.TYPE))) {
            register(jsonObject, ctx.channel().id());
        } else {
            sendToSomeone(jsonObject);
        }
    }

    //ping、pong
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //用于触发用户事件,包含触发读空闲、写空闲、读写空闲
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.ALL_IDLE) {
                Channel channel = ctx.channel();
                //关闭无用channel,以防资源浪费
                channel.close();
            }
        }
    }

    /**
     * 群发所有人
     */
    private void sendAllMessage(String message){
        //收到信息后,群发给所有channel
        MyChannelHandlerPool.channelGroup.writeAndFlush( new TextWebSocketFrame(message));
    }

    /**
     * 私聊
     */
    private void sendToSomeone(JSONObject map) {
        String toId = map.getString(MsgKey.TO_ID);
        ChannelId toChannelId = MyChannelHandlerPool.channelIdMap.get(toId);
        // 目标对象是否已下线,若ignore此元素,会造成自身session被关闭
        if (toChannelId != null) {
            Channel targetChannel = MyChannelHandlerPool.channelGroup.find(toChannelId);
            targetChannel.writeAndFlush(new TextWebSocketFrame(map.toString()));
        } else {
            log.warn("对方{}已下线", toId);
            JSONObject data = new JSONObject();
            data.put(MsgKey.FROM_ID, toId);
            data.put(MsgKey.STATE, MsgState.FAIL);
            data.put(MsgKey.MESSAGE, String.format("<发送失败>: 对方%s已下线", toId));
            String fromId = map.getString(MsgKey.FROM_ID);
            ChannelId fromChannelId = MyChannelHandlerPool.channelIdMap.get(fromId);
            Channel selfChannel = MyChannelHandlerPool.channelGroup.find(fromChannelId);
            selfChannel.writeAndFlush(new TextWebSocketFrame(data.toJSONString()));
        }
    }

    private void register(JSONObject map, ChannelId channelId) {
        String userId = map.getString(MsgKey.FROM_ID);
        MyChannelHandlerPool.channelIdMap.put(userId, channelId);
        log.info("{}注册后的连接:{}", userId, MyChannelHandlerPool.channelIdMap.keySet());
    }
}

2.4 自定义Channel连接池

package com.szh.wechat.ws;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class MyChannelHandlerPool {

    public MyChannelHandlerPool(){}

    /**
     * map: userId,ChannelId
     */
    public static Map<String, ChannelId> channelIdMap = new ConcurrentHashMap<>();

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

}

2.5 启动Netty服务器

package com.szh.wechat;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.szh.wechat.ws.MyWebSocketServer;

@SpringBootApplication
@MapperScan("com.szh.wechat.mapper")
public class WeChatApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(WeChatApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        new MyWebSocketServer(8001).start();
    }
}

2.6 配置客户端

代码略。与前文相差不多,可去Github查看,地址如下。

三、项目分享

【github地址】:https://github.com/oaHeZgnoS/wechat_web_netty

【相关技术】: SpringBoot、Netty、WebSocket、H5、JQuery等。

  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值