socket.io - 无法使用 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);
}
解决方案
在 io.on('connection') 之后,您必须使用从客户端接收消息
socket.on('welcome',(data) {
//from there emit to client receive message
}) ;
推荐阅读
- javascript - 如何使用选择标签有条件地渲染三个组件之一?
- sql - 在 SQL Server 中将多个列与相同条件进行比较的速记?
- android - Android 固定 RTL 和 LTR 方向
- mysql - 错误地选择十进制值
- sql - 从相同的数据中获取查询结果,但使用临时变量
- java - (JDK 11) 通过依赖于库的反射运行 JAR 存档
- node.js - 您是否尝试过嵌套模式?
- r - 如何识别函数是否在R中被递归调用
- ibm-mq - RFHUtil MQ 实用工具不支持 TLSV1.2 Cipher 以连接 MQ-9
- sql - 返回引用 ID 数最高的记录 Active Record