Socket.IO与服务器多次连接

Posted

技术标签:

【中文标题】Socket.IO与服务器多次连接【英文标题】:Socket.IO connecting multiple times with the server 【发布时间】:2021-08-22 20:02:35 【问题描述】:

我正在为我的家庭自动化构建一个应用程序,并发现 Socket.IO 存在问题。它在服务器端保持连接,但在客户端我无法获得任何事件:

expo version: 4.5.2
react-native-cli: 2.0.1
react-native: 0.63.4
node: v12.18.2
socket.io-client: 4.1.2

客户端代码:

import  io  from "socket.io-client";
const socket = io("http://my_local_ip:1337");
socket.on("connection", (data) => 
  console.log("Connected");
);
socket.on("response", (data) => console.log(data));

服务器:

const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);

server.listen(process.env.PORT, () => 
  console.log(`Listening on  Port: $server.address().port ... `);
);

io.on("connection", (socket) => 
  console.log("Connected: ", socket.id);
  socket.emit("response", "hello");

服务器输出:

Listening on  Port: 1337 ... 
Connected:  cH2smrT5EaFQrx6cAAAA
Connected:  hZAUEmGjCATQapC6AAAB
Connected:  i4jFNU_UFZnlQjjQAAAC
Connected:  eGma1MSRzmpfzlXrAAAD
Connected:  tz1UDL9ASJv5WdwgAAAE
Connected:  ygfDAyyMNjdQ-LSBAAAF
Connected:  FyQN9ZfqFaplbgOwAAAG
Connected:  PF8XNqjaG6GFkMQMAAAH
Connected:  aZ0q-uCoNxQbyYM4AAAI
Connected:  YaP7MFwFAcDjj54iAAAJ
Connected:  aYTCFJeMR2bSFvfyAAAK
Connected:  750GTXaUfs41RoJ-AAAL
Connected:  cD8T5fNkQZXk5_0SAAAM
Connected:  qYo8JlpPYltCB16YAAAN
Connected:  0nUW64Zi9lzsWIDiAAAO

客户端输出没有任何内容

【问题讨论】:

【参考方案1】:

你的客户端事件不合适,socket.io-client有以下事件:

socket.on("connect", () => 
    console.log("connected");
);

socket.on("data", (res) => 
    console.log(data);
);

【讨论】:

以上是关于Socket.IO与服务器多次连接的主要内容,如果未能解决你的问题,请参考以下文章

刷新后socket.io客户端多次监听同一事件

Socket.IO 在一个房间内多次发射(与 React.js 一起使用)

socket.io 发出多次

socket io客户端和服务器之间的连接问题

WebSockets(Socket.io)与heroku自动断开连接,我应该扩展吗?

android studio连接io.socket:sokect.io-client服务器的条件