apr*_*iak 2 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');
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');
});
Run Code Online (Sandbox Code Playgroud)
和我的简单客户:
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);
})
}
Run Code Online (Sandbox Code Playgroud)
如果我第三次点击,我会收到 3 条消息,依此类推。我做错了什么?我希望向服务器发送消息并接收修改后的消息。我是网络套接字的新手。
任何帮助表示赞赏。
PS 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);
})
}
Run Code Online (Sandbox Code Playgroud)
对此:
button.onclick = () => {
socket.emit('message', input.value);
}
socket.on('hello', (text) => {
const el = document.createElement('p');
el.innerHTML = text;
msg.appendChild(el);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4291 次 |
最近记录: |