Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot 如何指定服务器发送套接字消息?_Spring Boot_Socket.io - Fatal编程技术网

Spring boot 如何指定服务器发送套接字消息?

Spring boot 如何指定服务器发送套接字消息?,spring-boot,socket.io,Spring Boot,Socket.io,我目前正在构建一个Spring引导服务,它只向指定的服务器发送消息 我目前的代码如下 @Service(value = "socketIOService") public class SocketIOServiceImpl implements ISocketIOService { private static final Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>(

我目前正在构建一个Spring引导服务,它只向指定的服务器发送消息

我目前的代码如下

@Service(value = "socketIOService")
public class SocketIOServiceImpl implements ISocketIOService {

private static final Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();

private static final String PUSH_DATA_EVENT = "push_data_event";

@Autowired
private SocketIOServer socketIOServer;

@PostConstruct
private void autoStartup() {
    start();
}

@PreDestroy
private void autoStop() {
    stop();
}

@Override
public void start() {
    // Listen for client connections
    socketIOServer.addConnectListener(client -> {
        System.out.println("************ Client: " + getIpByClient(client) + " Connected ************");
        // Custom Events `connected` -> communicate with clients (built-in events such as Socket.EVENT_CONNECT can also be used)
        client.sendEvent("connected", "You're connected successfully...");
        String userId = getParamsByClient(client);
        if (userId != null) {
            clientMap.put(userId, client);
        }
    });

    // Listening Client Disconnect
    socketIOServer.addDisconnectListener(client -> {
        String clientIp = getIpByClient(client);
        System.out.println(clientIp + " *********************** " + "Client disconnected");
        String userId = getParamsByClient(client);
        if (userId != null) {
            clientMap.remove(userId);
            client.disconnect();
        }
    });

    // Custom Event`client_info_event` ->Listen for client messages
    socketIOServer.addEventListener(PUSH_DATA_EVENT, String.class, (client, data, ackSender) -> {
        // When a client pushes a `client_info_event` event, onData accepts data, which is json data of type string here and can be Byte[], other types of object
        String clientIp = getIpByClient(client);
        System.out.println(clientIp + " ************ Client:" + data);
    });

    socketIOServer.start();

    new Thread(() -> {
        while (true) {
            try {
                // Send broadcast message every 3 seconds
                Thread.sleep(3000);
                socketIOServer.getBroadcastOperations().sendEvent("myBroadcast", "Broadcast message ");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

@Override
public void stop() {
    if (socketIOServer != null) {
        socketIOServer.stop();
        socketIOServer = null;
    }
}

@Override
public void pushMessageToUsers(String msgContent) {
    for (String key : clientMap.keySet()) {

        SocketIOClient client = clientMap.get(key);
        if (client != null) {
            client.sendEvent(PUSH_DATA_EVENT, msgContent);
        }
    }
}

private String getParamsByClient(SocketIOClient client) {
    // Get the client url parameter (where userId is the unique identity)
    Map<String, List<String>> params = client.getHandshakeData().getUrlParams();
    List<String> userIdList = params.get("userId");
    if (!CollectionUtils.isEmpty(userIdList)) {
        return userIdList.get(0);
    }
    return null;
}

private String getIpByClient(SocketIOClient client) {
    String sa = client.getRemoteAddress().toString();
    return sa.substring(1, sa.indexOf(":"));
}
@Service(value=“socketIOService”)
公共类SocketIOServiceImpl实现了ISocketIOService{
私有静态最终映射clientMap=新的ConcurrentHashMap();
私有静态最终字符串PUSH\u DATA\u EVENT=“PUSH\u DATA\u EVENT”;
@自动连线
专用SocketIOServer SocketIOServer;
@施工后
私有void autoStartup(){
start();
}
@发情前期
私有void autoStop(){
停止();
}
@凌驾
公开作废开始(){
//侦听客户端连接
socketIOServer.addConnectListener(客户端->{
System.out.println(“*************客户端:“+getIpByClient(客户端)+”已连接**********”;
//自定义事件`connected`->与客户端通信(也可以使用Socket.EVENT\u CONNECT等内置事件)
sendEvent(“已连接”,“您已成功连接…”);
字符串userId=getParamsByClient(客户端);
if(userId!=null){
put(userId,client);
}
});
//侦听客户端断开连接
socketIOServer.addDisconnectListener(客户端->{
字符串clientIp=getIpByClient(client);
System.out.println(clientIp+“*******************”+“客户端已断开”);
字符串userId=getParamsByClient(客户端);
if(userId!=null){
clientMap.remove(userId);
client.disconnect();
}
});
//自定义事件`client\u info\u Event`->侦听客户端消息
socketIOServer.addEventListener(推送数据事件,String.class,(客户机,数据,ackSender)->{
//当客户端推送“client\u info\u event”事件时,onData接受数据,这是字符串类型的json数据,可以是Byte[],也可以是其他类型的对象
字符串clientIp=getIpByClient(client);
System.out.println(clientIp+“*************客户端:”+数据);
});
socketIOServer.start();
新线程(()->{
while(true){
试一试{
//每3秒钟发送一次广播信息
睡眠(3000);
socketIOServer.getBroadcastOperations().sendEvent(“myBroadcast”、“广播消息”);
}捕捉(中断异常e){
e、 printStackTrace();
}
}
}).start();
}
@凌驾
公共停车场(){
if(socketIOServer!=null){
socketIOServer.stop();
socketIOServer=null;
}
}
@凌驾
public void pushMessageToUsers(字符串msgContent){
for(字符串键:clientMap.keySet()){
SocketIOClient=clientMap.get(key);
如果(客户端!=null){
client.sendEvent(推送数据事件,msgContent);
}
}
}
私有字符串getParamsByClient(SocketIOClient客户端){
//获取客户端url参数(其中userId是唯一标识)
Map params=client.getHandshakeData().getUrlParams();
List userIdList=params.get(“userId”);
如果(!CollectionUtils.isEmpty(userIdList)){
返回userIdList.get(0);
}
返回null;
}
私有字符串getIpByClient(SocketIOClient){
字符串sa=client.getRemoteAddress().toString();
返回sa.substring(1,sa.indexOf(“:”);
}
}

这段代码来自我试图阅读的说明,但它们大多在中国…所以我无法解释

有没有关于限制和指定服务器以代码形式发送消息的建议

我想使用application.yml来指定发送消息的服务器


您的建议将不胜感激。

您只是想向特定客户发送websocket消息吗?@AndrewLeach是的,但socket.io的使用是必要的。