代码示例
- 根据netty的websoctet实现单聊
这里在传输的数据格式用文本转JSON的
@Override
protected void channelRead0(ChannelHandlerContext ctx,
TextWebSocketFrame msg) throws Exception { // (1)
ObjectMapper mapper = new ObjectMapper();
Message message = mapper.readValue(msg.text(), Message.class);
Channel incoming = ctx.channel();
if(null!=message) {
if(ChatType.BIND.equals(message.getCmd())){//绑定上线
ChannelManager.addChannel(message.getFrom(), incoming);
}else if(ChatType.LEAVE.equals(message.getCmd())) {
ChannelManager.removeChannelByCode(message.getFrom());
}else if(ChatType.SINGLE.equals(message.getCmd())) {
message.setMsg(HtmlUtils.htmlEscape(message.getMsg()));
if(null!=ChannelManager.getChannel(message.getAccept())) {
ChannelManager.getChannel(message.getAccept()).writeAndFlush(new TextWebSocketFrame(mapper.writeValueAsString(message)));
}else {
String from=message.getFrom();
message.setFrom(message.getAccept());
message.setAccept(from);
message.setMsg("["+message.getFrom()+"]未上线");
incoming.writeAndFlush(new TextWebSocketFrame(mapper.writeValueAsString(message)));
}
}else if(ChatType.GROUP.equals(message.getCmd())) {
message.setMsg(HtmlUtils.htmlEscape(message.getMsg()));
}else {
System.out.println("未识别的命令");
}
}
}
- 简单的数据格式
private String cmd;//1.绑定上线 2.下线 3.单聊 4.群聊
private String from;//用户ID
private String accept;//接受ID
private String group;//组ID
private String msg;//文本信息
- 效果
![](https://i-blog.csdnimg.cn/blog_migrate/f839a42239c2890cc05545490a9b38a7.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/773e14679469649848c232ffd31a9400.jpeg)