Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

node.js - Socket IO 3.0, Don't receive emit on server

Back Config

import express from "express";
import SocketIO from "socket.io";
import http from "http";
import cors from "cors";

const app = express();
app.use(cors());
const server = http.createServer(app);
const io = SocketIO(server);

const PORT = 5000;

io.on("connection", (socket) => {
  console.log("Connected!!");

  socket.on("send_message", (data) => {
    console.log('SEND_MESSAGE');
    console.log(data);
  });

  socket.on("disconnect", () => {
    console.log("Close.-.--.");
  });
});

server.listen(PORT, () => {
  console.log(`Server on port => ${PORT}`);
});

Front Implementation

import io from "socket.io-client";

let socket;

const Home = () => {
  useEffect(() => {
    socket = io("localhost:5000", {
      // transports: ["websocket"],
      // upgrade: false,
    });

    return () => socket.disconnect();
  }, []);


  const onEnter = () => {
    socket.emit("send_message", { message: messageToSend });
    setMessageToSend("");
  };


I receive the Connect and Disconnect emit's but i cant get the send_message emit, HELP! :c, i saw a few videos and courses can't get the result i want, don't judge me, im new with socket io

question from:https://stackoverflow.com/questions/65877885/socket-io-3-0-dont-receive-emit-on-server

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't know much of React but in the frontend, it should be:

socket = io.connect("http://localhost:9000");

Also, if it doesn't work then remove the disconnect code from the useEffect() and test it. If it is working means your socket get disconnected before emit event fires.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...