我遇到了 Node SocketIo 客户端不发送数据的问题。因此,当客户端在 index.html 中连接时确实记录了“Connected This Is A Test”,但是它没有 socket.emit('cool'),也没有错误,它似乎也没有登录 server.js。我不知道为什么它不发射或服务器不听。
Server.js
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const PORT = 3002;
app.use(express.static(path.join(__dirname, 'public')));
// run when client connects
io.on('connection', () => {
console.log('New WS connection...');
io.emit('connection', 'This Is A Test');
});
io.on('cool', (msg) => {
console.log(msg);
});
server.listen(PORT, () => console.log(`server running on port ${PORT}`));
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connection', function(data){
console.log("connected", data);
socket.emit('cool', 'MSG');
});
</script>
</body>
</html>
答案 0 :(得分:2)
在您的服务器上,您需要在特定连接的套接字上侦听 cool
消息,而不是在 io
对象上。除了宣布新连接的套接字之外,io
对象没有特定的套接字消息。要侦听来自特定套接字的消息,您需要在连接的套接字本身上有一个侦听器。添加该侦听器的通常位置是在 connection
事件中,您会在该事件中看到新连接的套接字对象。
所以改变这个:
// run when client connects
io.on('connection', () => {
console.log('New WS connection...');
io.emit('connection', 'This Is A Test');
});
io.on('cool', (msg) => {
console.log(msg);
});
为此:
// run when client connects
io.on('connection', (socket) => {
console.log('New WS connection...');
// send a test event back to the socket that just connected
socket.emit('test', 'This Is A Test');
// listen for the cool message on this new socket
socket.on('cool', (msg) => {
console.log(msg);
});
});
此外,您真的不应该发出系统使用的事件名称,例如 connection
。这就是我将事件名称更改为 test
的原因,这样它就不会与 socket.io 本身使用的名称冲突。