各语言socket.io 客户端
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>1.0.0</version>
</dependency>
package com.pojo.system.config;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pojo.common.core.utils.StringUtils;
import com.pojo.system.domain.SysMessage;
import com.pojo.system.service.SysMessageService;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Minio 配置信息
*
* @author ruoiy
*/
@Configuration
@ConfigurationProperties(prefix = "notice.im")
@Data
public class NoticeIMConfig {
/**
* 服务地址
*/
private String url;
@Autowired
SysMessageService sysMessageService;
@SneakyThrows
@Bean
public Socket getSocket() {
IO.Options options = new IO.Options();
options.transports = new String[]{"websocket"};
options.reconnectionAttempts = 2; // 重连尝试次数
options.reconnectionDelay = 1000; // 失败重连的时间间隔(ms)
options.timeout = 20000; // 连接超时时间(ms)
options.forceNew = true;
options.reconnection = true;
options.query = "userId=-1&clientType=APP&userName=Server"; //websocket传参
io.socket.client.Socket instance = IO.socket(url, options);
instance.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
for (Object arg : args) {
System.out.println(arg);
}
}
});
instance.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
}
});
//接收事件消息
instance.on("sysMessageUpdate", new Emitter.Listener() {
@Override
public void call(Object... objects) {
String messg = String.valueOf(objects[0]);
if (StringUtils.isNotBlank(messg)) {
JSONObject jsonObject = JSONObject.parseObject(messg);
String hkhiGroupId = jsonObject.getString("hkhjGroupId");
Long userId = Long.valueOf(jsonObject.getString("userId"));
String message = jsonObject.getString("messgae");
QueryWrapper<SysMessage> wrapper = new QueryWrapper<>();
wrapper.lambda().eq(SysMessage::getImId, hkhiGroupId)
.ne(SysMessage::getReceiveId, userId);
SysMessage sysMessage = SysMessage.builder()
.msgContent(message).build();
sysMessageService.update(sysMessage, wrapper);
}
}
});
return instance.connect();
}
}
socket.io服务端url
http://127.0.0.1:28889
发送消息
VideoAiMsg videoAiMsg = VideoAiMsg.builder().id(100L)
.type("aievent").build();
// videoai 服务端接收的事件名称 videoAiMsg 消息
socket.emit("videoai", new JSONObject(videoAiMsg) );
socket.io-client客户端文档