【问题标题】:Socket.io doesn't work with on event ("connection")Socket.io 不适用于 on 事件(“连接”)
【发布时间】:2021-03-12 02:18:17
【问题描述】:

我想在我的项目中使用socket-io,并在服务器上建立了它(node-js)和 客户端 (react) 但它似乎无法正常工作,并且在服务器上的控制台中,当用户连接时我看不到 user connected

app.js(服务器):

const express = require("express");
const app = express();
const PORT = process.env.PORT || 5000;

(async () => {
  await mongoConnect(error => {
    if (error) {
      console.log(error);
    } else {
      const server = app.listen(PORT, () =>
        console.log(`server is running on ${PORT} port`)
      );

      const io = require("./utils/socket-io/socket-io").initialSocket(server);

      io.on("connection", socket => {
        console.log("user connected");
      });
    }
  });
})();

socket-io.js(服务器):

const socketIo = require("socket.io");

let io;

module.exports = {
  initialSocket: server => {
    io = socketIo(server);
    return io;
  },
  getIo: () => {
    if (!io) {
      throw new Error("no connection to socket-io");
    }

    return io;
  }
};

posts.js(客户端):

import socketIo from "socket.io-client";

  useEffect(() => {
    socketIo("http://localhost:5000");
  }, [socketIo]);

【问题讨论】:

标签: node.js reactjs socket.io


【解决方案1】:

将您的app.js 编辑为此

const http = require('http');
const socketio = require('socket.io');

const app = express();
const server = http.createServer(app);         // This is going to allow us to create a new web server for express and we're going to it to our express application

const io = socketio(server);                   // Configure socketio to work with a given server
                                               // Now the server supports websockets


(async () => {
  await mongoConnect(error => {
    ...
    
    else {
      io.on("connection", socket => {
        console.log("user connected");
      });

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


【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
  • 2021-01-28
相关资源
最近更新 更多