I have an app where on the client side, you can send some information to the server, it will process the information, and then send a message back. My code is:
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST", "PUT", "DELETE"]
}
});
server.listen(3100, () => {
console.log("listening on *:3100");
});
// CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
io.on("connection", (socket) => {
console.log("a user connected");
socket.on("disconnect", () => {
console.log("user disconnected");
});
socket.on("setUp", (data) => {
//runs set-up functions
console.log("Setting up! " + data); //This appears in the console perfectly
io.emit("displayBasicText", "text");
});
socket.on("displayBasicText", (data, fn) => {
console.log("Your message is: " + data); //This never runs after "setUp"
io.emit("displayBasicText", data);
fn("ack");
});
});
When I emit "setUp" on the client side, the listener in my server will console.log just as it should and execute all other functions perfectly. However, the console.log in "displayBasicText" never occurs and the client never receives a message back.
If the client side emits "displayBasicText" directly -- without going through setUp -- then it also works perfectly and console.logs just fine. Because of this, I know that either "io.emit("displayBasicText...)" is not emitting or "displayBasicText" is not listening to "setUp".
I've looked in the Socket.io documentation but struggled to find an example of this. Any advice would be greatly appreciated!!
EDIT: I've tried socket.emit("displayBasicText", "text") and io.sockets.emit("displayBasicText", "text") and had the same result
