springboot集成t-io 实现客户端服务器通信

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在线测试地址

这里我们用两个websocket连接来测试,可以看到王麻子和李四都是已经连接成功了

ws://127.0.0.1:9326?userId=王麻子
ws://127.0.0.1:9326?userId=李四

在这里插入图片描述
在这里插入图片描述
接下来就可以发送信息测试一下。
在这里插入图片描述在这里插入图片描述

至此我们tio集成springBoot就简单实现了,接下来就是封装各自的业务逻辑了,tio是个很好的通信框架,上手难度较低,大家有条件的可以去支持一下官方文档。
Tio官网

有问题的地方可以提出

  • 1
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值