NodeJS 无法将节点js连接到socket.io

q3aa0525  于 2023-06-05  发布在  Node.js
关注(0)|答案(2)|浏览(218)

这是我的node.js应用程序设置。

require("dotenv").config();
const http = require("http");
const app = require("./app");
// const socketIO = require("socket.io");
const { Server } = require("socket.io");
const PORT = process.env.PORT || 4001;

const server = http.createServer(app);

//in case server and client run on different urls
const io = new Server(server, {
  cors: {
    origin: "http://localhost:3000",
  },
});

我认为这个io.on("connection")应该被调用。

io.on("connection", (socket) => {
  console.log("client connected: ", socket.id);

  socket.on("disconnect", (reason) => {
    console.log("Client disconnected:", socket.id, "Reason:", reason);
  });
});

server.listen(PORT, () => {
  console.info(`Server is start on http://localhost:${PORT}`);
});

Node.js没有连接socket.io。请帮帮我

jucafojl

jucafojl1#

你的代码看起来很好,你现在的工作是在客户端和服务器之间连接以启用socket.io。如果你使用ReactJS,你可以尝试:

import React, { useEffect } from 'react';
import socketIOClient from 'socket.io-client';

const App = () => {
  useEffect(() => {
    const socket = socketIOClient('http://localhost:4000');

    socket.on('connect', () => {
      console.log('Connected to the server.');
    });

    socket.on('disconnect', () => {
      console.log('Disconnected from the server.');
    });

    // Handle custom events here

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

  return <div>Your React.js application</div>;
};

export default App;
lpwwtiir

lpwwtiir2#

你的代码对我来说似乎很好。你试过用客户端连接服务器吗?。然后只有它才会显示为已连接。下面是一个示例客户端,您可以使用它连接到localhost。将其保存为index.html

<html>
<head>
<title>Socket.io Client</title>
</head>
<body>
<h1>Example socket.io client</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io();
</script>
</body>
</html>

相关问题