使用Netty实现IM消息聊天

一、项目引入netty依赖包

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.39.Final</version>
</dependency>

二、创建消息服务端

新建消息服务类IMServer

/**
 * 消息服务端
 */
public class IMServer {

    public static void start() throws InterruptedException {
        // 创建线程池组
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        // 初始化线程池和socket通道
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {

                    }
                });

        // 绑定端口
        bootstrap.bind(8126).sync();
    }
}

 创建消息服务端启动入口类IMApplication 

/**
 * 启动入口
 */
public class IMApplication {
    public static void main(String[] args) {
        IMServer.start();
    }
}

 启动后,可以用cmd命令 netstat -ano|findstr "8126"(端口号)查看是否启动成功 

三、添加通道处理器 

自定义一个通道处理器WebSocketHandler,打印一下客户端发送的消息,用于测试服务端是否能正常接受消息

/**
 * 自定义websocket处理器
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame frame) throws Exception {
        System.out.println(frame.text());
    }
}

 新建指令类:Command,根据不同的code来识别不同的消息业务

/**
 * 操作指令
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Command {

    /**
     * 业务编码
     */
    private Integer code;

    /**
     * 用户名称(唯一标识)
     */
    private String userName;
}

 新建指令枚举类:CommandTypeEnum

/**
 * 指令枚举
 */
@Getter
@AllArgsConstructor
public enum CommandTypeEnum {

    /**
     * 建立连接
     */
    CONNNECTION(10001),

    /**
     * 错误编码
     */
    ERROR(-1)
    ;

    private final Integer code;

    /**
     * 根据code查找枚举
     * @param code
     * @return
     */
    public static CommandTypeEnum match(Integer code){
        for (CommandTypeEnum value : CommandTypeEnum.values()){
            if (value.getCode().equals(code)){
                return value;
            }
        }
        return ERROR;
    }
}

使用在线websocket测试工具测试是否能连接上im消息服务器并发送消息

网址:websocket在线测试

 进入网址后使用websocket连接服务端并发送消息

四、 实现单聊消息

单聊模型图:

 总体思路:通过每个用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值