Websocket Socket.io发送两条消息

Websocket Socket.io发送两条消息,websocket,socket.io,Websocket,Socket.io,我正在尝试设置socket.io,这是我的server.js的一部分 const app = require('express')(); const http = require('http').Server(app); const io = require('socket.io')(http, { path: '/websocket', origins:'*:*' }); io.on('connection', (socket) => { socket.send('Hi'); sock

我正在尝试设置socket.io,这是我的server.js的一部分

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http, { path: '/websocket', origins:'*:*' });

io.on('connection', (socket) => {
socket.send('Hi');
socket.on('message', (message) => {
    console.log(message);
    socket.emit('hello', `New: ${message}`);
});
    console.log('a user connected');
});

http.listen(3030, function(){
   console.log('listening on *:3030');
});
我的简单客户:

var socket = io('https://*******.com', {
  secure: true,
  path: '/websocket'
});

const input = document.getElementById('text');
const button = document.getElementById('button');
const msg = document.getElementById('msg');

button.onclick = () => {
    socket.emit('message', input.value);
    socket.on('hello', (text) => {
        const el = document.createElement('p');
        el.innerHTML = text;
        msg.appendChild(el);
    })
}

如果我第三次点击,我会收到3条回复信息,以此类推。我做错了什么?我希望向服务器发送消息并接收修改后的消息。 我是网络套接字新手

谢谢你的帮助


p.S.socket.io v2.0.1

每次单击按钮时,您都会添加一个
socket.on()
事件处理程序。因此,在按钮被单击两次之后,您就有了重复的
socket.on()
事件处理程序。当事件返回时,您的两个事件处理程序将分别被调用,您将认为您收到了重复的消息。事实上,它只是一条消息,但具有重复的事件处理程序

您几乎不希望在另一个事件处理程序中添加事件处理程序,因为这会导致这种重复事件处理程序的构建。你没有(用语言)确切地描述你的代码试图做什么,所以我不知道确切地建议什么替代方案。通常,在连接套接字时,首先设置事件处理程序,仅设置一次,然后将永远不会得到重复的处理程序

所以,也许这就像改变这一点一样简单:

button.onclick = () => {
    socket.emit('message', input.value);
    socket.on('hello', (text) => {
        const el = document.createElement('p');
        el.innerHTML = text;
        msg.appendChild(el);
    })
}
为此:

button.onclick = () => {
    socket.emit('message', input.value);
}

socket.on('hello', (text) => {
    const el = document.createElement('p');
    el.innerHTML = text;
    msg.appendChild(el);
});

如果您使用Angular并(可能)将套接字嵌入服务(simpleton),那么每次加载页面时,您都会在ngOnInit中创建一个持久侦听器


您需要创建某种标志,以了解侦听器是否已从页面的另一个实例在服务中创建。

谢谢!你救了我一天。@jfriend00 Awsome。。。你拯救了我们的一天。