【问题标题】:Can't send a message from server to client with socket.io无法使用 socket.io 从服务器向客户端发送消息
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 和从客户端同样的socket.on函数接收消息给客户端
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2013-09-09
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    相关资源
    最近更新 更多