【发布时间】:2021-10-10 23:29:51
【问题描述】:
我是 socket.io 的新手,我正在尝试按照https://socket.io/docs/v4/emitting-events/ 上的基本发射说明从服务器向客户端发送消息。我希望当我连接到套接字时,我会在控制台上打印“世界”这个词,但我不知道为什么失败了。我是不是做错了什么?
服务器
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
io.emit('welcome', 'world');
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});
客户
var socket = io();
socket.on('welcome', (arg) => {
console.log(arg);
}
【问题讨论】:
标签: socket.io