一、TioClient初始化
1.获取IM服务器地址
// 创建Tio客户端
TioClient mClient = new TioClient();
ImServerAddress address = mClient.requestAddress(null);
String ip = address.getIp();
int port = address.getPort();
2.初始化TioClient配置
- ip: IM服务器ip
- port: IM服务器port
- groupId: 群组id(可以为空)
- timeout: 连接超时时长(单位毫秒;默认15000毫秒)
- heartBeatInterval: 心跳间隔(单位秒;默认60秒;至少1秒)
- reconnectInterval: 重连间隔(单位秒;默认3秒;至少1秒)
mClient.initConfig(new TaoIMConfig.Builder(ip, port)
.setTimeout(timeout)
.setHeartBeatInterval(heartBeatInterval)
.setReconnectInterval(reconnectInterval)
.build());
3.设置握手请求
- token: 客户端通过http登录后,服务器返回给客户端的token值
- handshakeKey: 握手请求密钥,存在:org.tio.sitexxx.service.vo.Const.HANDSHAKE_KEY中,可以修改,但要保证客户端和服务器端用的这个值是一样的
- cid: 渠道
// 内部会自动创建握手请求消息包,并发送
mClient.setTioHandshake(new TioHandshake.Builder(token, handshakeKey)
.setActivity(activity)
.setCid(cid)
.build());
4.设置“命令码所对应的消息体”Map
// Short为消息命令码,Class为消息体字节码
Map<Short, Class> commandBodyMap = new HashMap<>();
commandBodyMap.put(TioCommand.HANDSHAKE_RESP.getValue(), HandshakeResp.class);
commandBodyMap.put(TioCommand.JOIN_GROUP_RESP.getValue(),JoinGroupResp.class);
...
mClient.setCommandBodyMap(commandBodyMap);
5.注册回调,接收消息
//注册监听
mClient.registerTioCallback(new TioSimpleClientCallback() {
// IM连接成功
@Override
public void onConnected(TioClient client) {
}
// IM断开连接
@Override
public void onDisconnected(TioClient client) {
}
// IM连接出错
@Override
public void onError(TioClient client, Exception e) {
}
// IM发送一个消息包完成
@Override
public void onSendEnd(TioClient client, TioPacket packet) {
}
// IM接收一个消息包完成
@Override
public void onReceiveEnd(TioClient client, TioPacket packet, Object body) {
if (packet.getCommand() == TioCommand.HANDSHAKE_RESP.getValue()) {
HandshakeResp handshakeResp = (HandshakeResp) body;
// TODO 握手响应
} else if (packet.getCommand() == TioCommand.JOIN_GROUP_RESP.getValue()) {
JoinGroupResp joinGroupResp = (JoinGroupResp) body;
// TODO 加入群组响应
}
}
});
二、TioClient基本操作
开始连接
mClient.connect();
断开连接
mClient.disconnect();
获取连接状态
TaoIMState imState = mClient.getState()
发消息
client.sendPacket(packet)
三、TioClient资源释放
@Override
protected void onDestroy() {
super.onDestroy();
if (mClient != null) {
mClient.release();
mClient = null;
}
}