使用tio编写建议的websocket聊天室后台
[官方文档](https://www.tiocloud.com/doc/tio/?pageNumber=1)
maven引入
<dependency>
<groupId>org.t-io</groupId>
<artifactId>tio-websocket-server</artifactId>
<version>3.5.9.v20200214-RELEASE</version>
</dependency>
MyWsMsgHandler 处理类
package com.wlq.demo.conf;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.wlq.demo.uitls.RedisHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.utils.lock.SetWithLock;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.server.handler.IWsMsgHandler;
import java.util.ArrayList;
import java.util.HashMap;
@Component
public class MyWsMsgHandler implements IWsMsgHandler {
@Autowired
private RedisHelper redisHelper;
@Override
public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
return httpResponse;
}
@Override
public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
String id = httpRequest.getParam("userId");
String receiver = httpRequest.getParam("receiver");
String chatType = httpRequest.getParam("chatType");
channelContext.setAttribute("chatType",chatType);
channelContext.setAttribute("receiver",receiver);
Tio.bindUser(channelContext, id);
SetWithLock<ChannelContext> lock = Tio.getChannelContextsByUserid(channelContext.tioConfig, id);
JSONObject message = new JSONObject();
message.put("msg", "连接成功...");
message.put("sendName", "系统提醒");
WsResponse wsResponse = WsResponse.fromText(message.toString(), "UTF-8");
Tio.sendToUser(channelContext.tioConfig, id, wsResponse);
}
@Override
public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
String sendNameId = channelContext.userid;
String receiverId = String.valueOf(channelContext.getAttribute("receiver"));
String chatType = String.valueOf(channelContext.getAttribute("chatType"));
JSONObject message = new JSONObject();
message.put("receiver",receiverId);
message.put("sendName",sendNameId);
message.put("msg","这是图片");
String time = DateUtil.format(DateTime.now(), DatePattern.NORM_DATETIME_PATTERN);
message.put("time",time);
message.put("chatType",chatType);
JSONArray list = new JSONArray();
Object o;
if (Boolean.parseBoolean(chatType)){
o = redisHelper.get(receiverId);
if (null == o) {
list.add(message.toString());
redisHelper.set(receiverId,list.toString());
}else {
JSONArray array = JSONUtil.parseArray(o);
array.add(message.toString());
redisHelper.set(receiverId, array.toString());
}
}else {
o = redisHelper.get(sendNameId);
if (null == o) {
list.add(message.toString());
redisHelper.set(sendNameId,list.toString());
}else {
JSONArray array = JSONUtil.parseArray(o);
array.add(message.toString());
redisHelper.set(sendNameId, array.toString());
}
}
System.out.println("我走了onBytes");
return null;
}
@Override
public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
String chatType = String.valueOf(channelContext.getAttribute("chatType"));
if (!Boolean.parseBoolean(chatType)){
Object chatLog = channelContext.getAttribute("chatLog");
JSONArray array = JSONUtil.parseArray(chatLog);
}
Tio.remove(channelContext, "WebSocket Close");
return null;
}
@Override
public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
JSONObject message = new JSONObject();
String sendNameId = channelContext.userid;
message.put("sendName",sendNameId);
String receiverId = String.valueOf(channelContext.getAttribute("receiver"));
message.put("receiver",receiverId);
message.put("msg",text);
String time = DateUtil.format(DateTime.now(), DatePattern.NORM_DATETIME_PATTERN);
message.put("time",time);
String chatType = String.valueOf(channelContext.getAttribute("chatType"));
message.put("chatType",chatType);
JSONArray list = new JSONArray();
Object o;
if (Boolean.parseBoolean(chatType)){
o = redisHelper.get(receiverId);
if (null == o) {
list.add(message.toString());
redisHelper.set(receiverId,list.toString());
}else {
JSONArray array = JSONUtil.parseArray(o);
array.add(message.toString());
redisHelper.set(receiverId, array.toString());
}
}else {
o = redisHelper.get(sendNameId);
if (null == o) {
list.add(message.toString());
redisHelper.set(sendNameId,list.toString());
}else {
JSONArray array = JSONUtil.parseArray(o);
array.add(message.toString());
redisHelper.set(sendNameId, array.toString());
}
}
channelContext.setAttribute("chatLog",list);
WsResponse wsResponse = WsResponse.fromText(message.toString(), "UTF-8");
Tio.sendToUser(channelContext.tioConfig, receiverId, wsResponse);
JSONObject resp = new JSONObject();
resp.put("sendName", "系统提醒");
resp.put("msg", "发送成功");
return resp.toString();
}
}
WebSocketConfig 配置类
package com.wlq.demo.conf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.tio.server.ServerTioConfig;
import org.tio.websocket.server.WsServerStarter;
import java.io.IOException;
@Configuration
public class WebSocketConfig {
@Autowired
private MyWsMsgHandler myWsMsgHandler;
@Bean
public WsServerStarter wsServerStarter() throws IOException {
WsServerStarter wsServerStarter = new WsServerStarter(6789, myWsMsgHandler);
ServerTioConfig serverTioConfig = wsServerStarter.getServerTioConfig();
serverTioConfig.setHeartbeatTimeout(1000 * 120);
wsServerStarter.start();
return wsServerStarter;
}
}