【问题标题】:Socket.io-client is not connecting to socket.io server react and node(express)Socket.io-client 未连接到 socket.io 服务器反应和节点(快递)
【发布时间】:2021-04-21 23:24:57
【问题描述】:

我尝试使用以下代码连接到 socket.io-client:

客户:

import queryString from 'query-string';
import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';

let socket;

const Chat = ({location}) => {

const [name, setName] = useState("");
const [room, setRoom] = useState("");
const EP = 'http://localhost:5000/';

useEffect(() =>{
    const {name , room} = queryString.parse(location.search);

    socket = io(EP);

    setName(name);
    setRoom(room);

    console.log(socket);
},[EP, location.search])

return(
    <h1>helloooooooooooooo {name} welcome to {room}</h1>
)
}

export default Chat;

服务器:

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

const PORT = process.env.PORT ||5050;

const app = express();
const server = http.createServer(app);
const io = socketio(server);




//socket.io

io.on('connection', socket => {
console.log("we have a new user!!!!!!!!!");

socket.on('disconnect', () =>{
    console.log('User had left!');
})
})

// io.on('connection', socket => { 
//     console.log("we have a new user!!!!!!!!");

//     socket.on("disconnect", () => console.log("user is left"))        
//  });

app.use(router);

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

我没有从这个服务器套接字获取连接或断开控制台日志。 我遵循与 socke.io doc 相同的流程。

console message from browser, its showing disconnected true and connected false and no id

【问题讨论】:

    标签: node.js reactjs express socket.io


    【解决方案1】:

    在浏览器中,WebSocket 对象不支持附加标头。如果您想添加一些标头作为某些身份验证机制的一部分,您可以使用transportOptions 属性。请注意,在这种情况下,标头不会在 WebSocket 升级请求中发送。

     // WILL NOT WORK in the browser
        const socket = new Socket('http://localhost', {
          extraHeaders: {
            'X-Custom-Header-For-My-Project': 'will not be sent'
          }
        });
        // WILL NOT WORK
        const socket = new Socket('http://localhost', {
          transports: ['websocket'], // polling is disabled
          transportOptions: {
            polling: {
              extraHeaders: {
                'X-Custom-Header-For-My-Project': 'will not be sent'
              }
            }
          }
        });
        // WILL WORK
        const socket = new Socket('http://localhost', {
          transports: ['polling', 'websocket'],
          transportOptions: {
            polling: {
              extraHeaders: {
                'X-Custom-Header-For-My-Project': 'will be used'
              }
            }
          }
        });
    

    信用:Engine.IO client

    【讨论】:

      【解决方案2】:

      在客户端,在 useEffect 内部而不是

      socket = io(EP);
      

      到这里

      socket = io.connect(EP , {
              "force new connection" : true,
              "reconnectionAttempts": "Infinity", 
              "timeout" : 10000,                  
              "transports" : ["websocket"],
              withCredentials:true,
                  extraHeaders:{
                      "my-custom-header": "abcd"
                  }
          });
      

      i got this solution from this question

      【讨论】:

        【解决方案3】:

        从 Socket.IO v3 开始,您需要显式启用跨域资源共享 (CORS)。 https://socket.io/docs/v3/handling-cors/

        // server-side
        const io = require("socket.io")(httpServer, {
          cors: {
            origin: "https://example.com",
            methods: ["GET", "POST"],
            allowedHeaders: ["my-custom-header"],
            credentials: true
          }
        });
        
        // client-side
        const io = require("socket.io-client");
        const socket = io("https://api.example.com", {
          withCredentials: true,
          extraHeaders: {
            "my-custom-header": "abcd"
          }
        });
        

        【讨论】:

        • 非常感谢,我尝试了很多方法,我仔细阅读了套接字文档,但不幸的是仍然没有工作。仍然没有连接。
        猜你喜欢
        • 2015-05-20
        • 2021-03-31
        • 1970-01-01
        • 1970-01-01
        • 2018-03-14
        • 2023-03-18
        • 2016-05-12
        • 2020-04-27
        • 2020-05-11
        相关资源
        最近更新 更多