Socket IO服务器重新启动导致客户端发出重复的事件。

huangapple go评论64阅读模式
英文:

Socket IO server restart causes duplicate client emits

问题

当我对我的Node/Socket IO服务器进行更改并重新启动时,连接的客户端会开始发送两条消息,而不是一条。如果我再次重新启动,它会开始发送三条消息,依此类推。

我唯一看到的“解决方法”是刷新客户端页面以强制建立新连接。

如何防止客户端在服务器重新启动后发送多个消息?

非常标准的设置:

服务器

const app = express();
const port = process.env.PORT || 4000;
const server = app.listen(port, () => console.log(`Server started on port ${port}`));
const io = require('socket.io').listen(server);

app.get('/', (req, res) => {
   res.sendFile('/public/index.html', { root: __dirname });
});

io.on('connection', client => client.on('event', (msg) => console.log(msg)));

客户端

const socket = io.connect('', { query: { path: window.location.pathname }, reconnect: false, forceNew: true });

$("body").on("click", "a", () => socket.emit('event', 'test'));

请注意,上述代码是JavaScript代码,不需要翻译。

英文:

When I make changes to my Node/Socket IO server and restart it, the connected client will start emitting two messages for each one. If I restart again, it will start emitting three, and so forth.

The only "fix" I see is to refresh the page on client to force a new connection.

How do I prevent the client from emitting multiple messages after a server restart?

Pretty standard setup:

Server

const app = express();
const port = process.env.PORT || 4000;
const server = app.listen(port, () => l(`Server started on port ${port}`));
const io = require('socket.io').listen(server);

app.get('/', (req, res) => {
   res.sendFile('/public/index.html', { root: __dirname });
});

io.on('connection', client => client.on('event', (msg) => console.log(msg));

Client

const socket = io.connect('', { query: { path: window.location.pathname }, reconnect: false, forceNew: true });

$("body").on("click", "a", () => socket.emit('event', 'test'));

答案1

得分: 2

这是解决方案:
https://github.com/socketio/socket.io/issues/430#issuecomment-451130988

不要将 socket.on 包装在像 connect 或 authenticated 这样的操作中。

在我的示例中,我将 "socket.on" 包装在授权中。一旦客户端重新连接,"socket.on" 会叠加并在服务器重新启动时每次都增加。

英文:

Here is the solution:
https://github.com/socketio/socket.io/issues/430#issuecomment-451130988

Don't wrap the socket.on in actions like connect or authenticated.

In my example I had a "socket.on" wrapped in authorization. As soon as the client reconnected the socket.on stacked up and multiplied each time the server restarted.

huangapple
  • 本文由 发表于 2020年1月3日 23:24:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定