一、配置socketIO服务
@Component
public class Server {
@Value("${wss.server.host}")//socket服务地址
private String host;
@Value("${wss.server.port}")//socket服务端口
private Integer port;
@Bean
private SocketIOServer socketIOServer() {
Configuration config = new Configuration();
config.setHostname(host);
config.setPort(port);
final SocketIOServer server = new SocketIOServer(config);
return server;
}
@Bean
private SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
return new SpringAnnotationScanner(socketServer);
}
}
配置好服务之后需要启动
二、启动socketIO服务
@Component
public class ServerRunner implements CommandLineRunner {
private final LogHandler logger = new LogHandler(this.getClass().getName());
private final SocketIOServer server;
@Autowired
public ServerRunner(SocketIOServer server) {
this.server = server;
}
@Override
public void run(String... args) throws Exception {
logger.info("~~~~socket-IO server启动~~~~");
server.start();
}
}
这样socketIO的服务就已经启动
三、socketio消息交互
@EnableScheduling
@Component
public class MessageEventHandler {
//客户端存储
private static List<SocketIOClient> clients = new ArrayList<SocketIOClient>();// 用于保存所有客户端
private final LogHandler logger = new LogHandler(this.getClass().getName());
@Autowired
private IStateDisplayService displayService;
//添加connect事件,当客户端发起连接时调用
@OnConnect
private void messageHandler(SocketIOClient client) {
logger.info("connected:SessionId=" + client.getSessionId());
//存储监听到的客户端
clients.add(client);
}
/**
* 向socket客户端发送消息
*
* @param resultMap
*/
public void sendMsg(String key, Map<String, Object> resultMap) {
clients.removeIf(client -> !client.isChannelOpen());//删除已断开的客户端
for (SocketIOClient client : clients) {
client.sendEvent(key, resultMap);//向客户端发送数据
}
}
/**
* 获取机器状态
*以机器这个例子展示交互
*/
@Scheduled(fixedRate = 10000)
public void sendMachine() {
Map<String, Object> resultMap = displayService.getMachineState();
sendMsg("bvMachineState", resultMap);
}
网友评论