2017-05-24 122 views
0

我试图建立socket.io,这里是我的server.jsSocket.io发送两个消息

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); 
    }) 
} 

enter image description here

如果我第三次点击,我会收到3封邮件,依此类推。我做错了什么?我希望将消息发送到服务器并接收修改后的消息。 我是新的网络套接字。

任何帮助表示赞赏。

P.S. socket.io v2.0.1

回答

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); 
}); 
+0

谢谢!你节省了我的一天。 –