一、项目引入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连接服务端并发送消息
四、 实现单聊消息
单聊模型图:
总体思路:通过每个用