I'm learning the socket.io
library in Node.js
and I can't make the server receive data, only send. During tests I noticed that the io.on
listener function isn't even being called, and I don't know where's my mistake. What exactly works and what doesn't is marked with commentaries in the code bellow.
My server-side code:
"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);
My client-side code:
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
}
My client-side 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>
based on the doc https://socket.io/docs/v4/client-socket-instance/
the connection event is connection
on server side, and connect
on client side
// 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
});
for Emit events, if you see here https://socket.io/docs/v4/emitting-events/
it seems requires us to put the subscription event inside connection
block
// server-side
io.on("connection", (socket) => {
socket.on("hello", (arg) => {
console.log(arg); // world
});
});
// client-side
socket.emit("hello", "world");
so maybe you can try to change your server code
io.on("connection", (socket) => {
socket.on("sendMsg", msg => { // This doesn't work
log("sendMsg: " + msg);
}
});
it uses socket.on
, not io.on
on server side