无法将NodeJS连接到socket.io。

huangapple go评论76阅读模式
英文:

Cannot connect NodeJS to socket.io

问题

这是我的NodeJS应用程序设置

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);
// 以防服务器和客户端运行在不同的URL上。
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}`);
});

NodeJS没有连接到socket.io。 请帮助我。

英文:

This my NodeJS application setup

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",
  },
});

I think this io.on("connection") should called

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}`);
});

NodeJS is not connecting socket.io. Please help me.

答案1

得分: 0

你的代码看起来对我来说没问题。你尝试过使用客户端连接到你的服务器了吗?只有这样才会显示为已连接。这是一个示例客户端,你可以用它连接到本地主机。将其保存为 index.html

<!DOCTYPE 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>
英文:

your code seems to be fine to me. Have you tried connecting to your server with a client?. Then only it will show as connected. Here is an example client you can use to connect to localhost. Save this as index.html

&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Socket.io Client&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Example socket.io client&lt;/h1&gt;
&lt;script src=&quot;/socket.io/socket.io.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
  const socket = io();
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

答案2

得分: 0

你的代码看起来没问题,现在你的任务是连接客户端和服务器以启用 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.');
    });

    // 在这里处理自定义事件

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

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

export default App;

希望这有所帮助。

英文:

your code seems to be fine, your job now is to connect between client and server to enable socket.io. If you use ReactJS you can try:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import React, { useEffect } from &#39;react&#39;;
import socketIOClient from &#39;socket.io-client&#39;;

const App = () =&gt; {
  useEffect(() =&gt; {
    const socket = socketIOClient(&#39;http://localhost:4000&#39;);

    socket.on(&#39;connect&#39;, () =&gt; {
      console.log(&#39;Connected to the server.&#39;);
    });

    socket.on(&#39;disconnect&#39;, () =&gt; {
      console.log(&#39;Disconnected from the server.&#39;);
    });

    // Handle custom events here

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

  return &lt;div&gt;Your React.js application&lt;/div&gt;;
};

export default App;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月1日 02:19:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定