springboot集成t-io 实现客户端服务器通信
jdk 1.8 t-io 3.6 idea 2019
POM依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/>
</parent>
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.0.0</maven-jar-plugin.version>
<t-io.version>3.6.0.v20200315-RELEASE</t-io.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<dependency>
<groupId>org.t-io</groupId>
<artifactId>tio-websocket-spring-boot-starter</artifactId>
<!--此版本号跟着tio主版本号一致即可-->
<version>${t-io.version}</version>
</dependency>
<dependency>
<groupId>org.t-io</groupId>
<artifactId>tio-utils</artifactId>
<version>${t-io.version}</version>
</dependency>
</dependencies>
application.yml文件
tio:
websocket:
server:
ip: 127.0.0.1
port: 9326
heartbeat-timeout: 600000
启动类,加上@EnableTioWebSocketServer即可
核心处理代码
package cn.theone.tmp.tio;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Component;
import org.tio.common.starter.annotation.TioServerMsgHandler;
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.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.server.handler.IWsMsgHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author : zgc
* @date : 2020/8/17 14:44
* @versions : 1.0
* @project theone-xwyj
* @content
*/
@TioServerMsgHandler
@Component
public class TioWebSocket implements IWsMsgHandler {
private static Map<String, ChannelContext> userSocketMap = new ConcurrentHashMap<>();
@Override
public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
return httpResponse;
}
//http握手成功后触发该方法,一般用于绑定一些参数
@Override
public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
Message message = new Message();
String userId = httpRequest.getParam("userId");
if (userSocketMap.get(userId) == null) {
userSocketMap.put(userId, channelContext);
Tio.bindUser(channelContext, userId);
message.setSuccess(true);
message.setMsg(userId + " 连接成功!");
message.setCode(0);
message.setMsgType(3);
} else {
userSocketMap.put(userId, channelContext);
Tio.bindUser(channelContext, userId);
message.setSuccess(false);
message.setMsg(userId + " 请勿重复连接!");
message.setCode(107);
message.setMsgType(3);
}
//用tio-websocket,服务器发送到客户端的Packet都是WsResponse
WsResponse wsResponse = WsResponse.fromText(JSON.toJSONString(message), "UTF-8");
System.out.println("收到消息:" + JSON.toJSONString(message));
//点对点发送
if (userSocketMap != null && userSocketMap.size() > 0) {
Tio.sendToUser(channelContext.tioConfig, userId, wsResponse);
} else {
Tio.send(channelContext, wsResponse);
}
}
@Override
public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
return null;
}
@Override
public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
return null;
}
@Override
public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
if (Objects.equals("心跳内容", text)) {
return null;
}
//服务器发送到客户端的Packet都是WsResponse
Message tioSendMessage = JSONArray.parseObject(text, Message.class);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
tioSendMessage.setReceiveTime(sdf.format(new Date()));
WsResponse wsResponse;
wsResponse = WsResponse.fromText(JSONArray.toJSONString(tioSendMessage), "UTF-8");
Tio.sendToUser(channelContext.tioConfig, tioSendMessage.getToUserID(), wsResponse);
tioSendMessage.setSuccess(true);
tioSendMessage.setMsg("发送个人消息成功!");
tioSendMessage.setMsgType(3);
System.out.println("收到客户端发来信息:" + JSONArray.toJSONString(tioSendMessage));
return JSONArray.toJSONString(tioSendMessage);
}
}
Message消息体
package cn.theone.tmp.tio;
import java.io.Serializable;
/**
* Socket 发送消息模板
*/
public class Message implements Serializable {
private static final long serialVersionUID = 1L;
private Integer msgType; // 0事件信息 1预警信息 2地图同步 3系统返回信息 4心跳监测
private Integer sendType;// 1发送 0接收
private Boolean success;
private String msg;
private Object data;
private Integer code;
private String toUserID;//接收人ID
private String receiveTime;//接收时间
public Message() {
}
public Message(Integer msgType, Object data) {
this.msgType = msgType;
this.data = data;
}
public String getToUserID() {
return toUserID;
}
public void setToUserID(String toUserID) {
this.toUserID = toUserID;
}
public String getReceiveTime() {
return receiveTime;
}
public void setReceiveTime(String receiveTime) {
this.receiveTime = receiveTime;
}
public Integer getMsgType() {
return msgType;
}
public void setMsgType(Integer msgType) {
this.msgType = msgType;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getSendType() {
return sendType;
}
public void setSendType(Integer sendType) {
this.sendType = sendType;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
至此一个简单的消息处理已经完成了,接下来我们可以测试一下
这里我们用两个websocket连接来测试,可以看到王麻子和李四都是已经连接成功了
ws://127.0.0.1:9326?userId=王麻子
ws://127.0.0.1:9326?userId=李四
接下来就可以发送信息测试一下。
至此我们tio集成springBoot就简单实现了,接下来就是封装各自的业务逻辑了,tio是个很好的通信框架,上手难度较低,大家有条件的可以去支持一下官方文档。
Tio官网
有问题的地方可以提出