为啥我的服务器没有监听客户端发出的数据?
Posted
技术标签:
【中文标题】为啥我的服务器没有监听客户端发出的数据?【英文标题】:Why my server isn't listening the data emitted from client?为什么我的服务器没有监听客户端发出的数据? 【发布时间】:2021-10-09 23:45:45 【问题描述】:我正在学习Node.js
中的socket.io
库,无法让服务器接收数据,只能发送。在测试期间,我注意到 io.on
监听器函数甚至没有被调用,我不知道我的错误在哪里。下面代码中的注释标记了哪些确切有效,哪些无效。
我的服务器端代码:
"use strict";
const http = require("http");
const express = require("express");
const Server = require("socket.io");
const log = console;
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(express.urlencoded(extended: false));
app.use(express.json());
app.use(express.static(__dirname + "/public"));
io.on("connect", socket =>
const id = socket;
io.emit("receiveMsg", id); // This works
)
io.on("sendMsg", msg => // This doesn't work
log("sendMsg: " + msg);
);
server.listen(8080);
我的客户端代码:
const socket = io();
const log = console;
socket.on("receiveMsg", msg => // This works
log("receiveMsg: " + msg);
);
const sendMsg = () =>
const msg = document.querySelector("#msg").value;
socket.emit("sendMsg", msg); // This doesn't work
我的客户端 html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<h1>Hello, world!</h1>
<input type="text" id="msg" placeholder="msg">
<button onclick="sendMsg()">send</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script>
<script>
// Client-side code here
</script>
</body>
</html>
【问题讨论】:
【参考方案1】:基于文档https://socket.io/docs/v4/client-socket-instance/
连接事件在服务器端是connection
,在客户端是connect
// server-side
io.on("connection", (socket) =>
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
);
// client-side
socket.on("connect", () =>
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
);
对于 Emit 事件,如果您在此处看到 https://socket.io/docs/v4/emitting-events/
似乎需要我们将订阅事件放在connection
块中
// server-side
io.on("connection", (socket) =>
socket.on("hello", (arg) =>
console.log(arg); // world
);
);
// client-side
socket.emit("hello", "world");
所以也许您可以尝试更改您的服务器代码
io.on("connection", (socket) =>
socket.on("sendMsg", msg => // This doesn't work
log("sendMsg: " + msg);
);
它在服务器端使用socket.on
,而不是io.on
【讨论】:
以上是关于为啥我的服务器没有监听客户端发出的数据?的主要内容,如果未能解决你的问题,请参考以下文章
为啥oracle 远程连接不上,本地可以登录?没有防火墙。服务器也ping的通