gpt4 book ai didi

javascript - 通过外部触发将数据推送到web socket

转载 作者:行者123 更新时间:2023-11-28 04:14:22 25 4
gpt4 key购买 nike

我想在调用 REST API 时将数据推送到所有连接的套接字

我有一个基于 Express 的 Node js 应用程序。

在应用程序启动时,我创建了文档中提到的套接字服务器。

客户端代码

var socket = io('http://localhost');
socket.emit('client_id', 'test');
socket.on('message', function (message) {
console.log(message);
});

服务器代码

io.on('connection', function (socket) {
socket.on('client_id', function (client_id) {
socket.join(client_id);
});
});

API调用

io.sockets.to('client_name').emit('message', 'Some message');  

问题是,当我启动节点/套接字服务器并启动客户端时,这工作正常。

但是当我重新启动节点/套接字服务器时,客户端不再收到消息。我必须重新加载客户端才能开始接收消息。

可能是什么问题

最佳答案

commented在这个问题下,我将尝试解释您提供的代码到底发生了什么。另外我想向您建议一个解决方案 your comment

// With the following line of code you connect to the server
var socket = io('http://localhost');

// Now you send the client_id and it is sent only once per page load
socket.emit('client_id', 'test');

// And here subscribe to the message event
socket.on('message', function (message) {
console.log(message);
});

// ----------------------------------------
// now we change the above code like

var socket = io('http://localhost');
socket.on('connect', function(){
// emit the event client_id every time you connect
socket.emit('client_id', 'test');
socket.on('message', function (message) {
console.log(message);
});
});

您需要将代码包装在 on('connect', ...) 订阅中,以确保每次连接到服务器时都会发送 client_id 。否则 client_id 仅在加载客户端代码时发送一次。

如果您想避免重复消息,如 your comment 中所述,您可以更新服务器端代码,例如:

// Save reference to client_id by socket.id
var clientIds = {};
io.on('connection', function (socket) {

socket.on('client_id', function (client_id) {
clientIds[socket.id] = client_id;
socket.join(client_id);
});

// Subscribe to disconnect event and leave the room once client is disconnected
socket.on('disconnect', function (reason) {
// leave the room
socket.leave(clientIds[socket.id]);
});

});

使用上述代码,您可以确保在客户端断开连接后立即离开房间。

如果有不清楚的地方,请告诉我。祝你好运!

关于javascript - 通过外部触发将数据推送到web socket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45996107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com