首页 > 解决方案 > 无法使用 socket.io 从服务器向客户端发送消息

问题描述

我是 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

解决方案


在 io.on('connection') 之后,您必须使用从客户端接收消息

socket.on('welcome',(data) {
     //from there emit to client receive message
}) ;

推荐阅读