0

I try to connect to a socket.io-client using the following code:

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;

server:

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

i dont get connet or disconnect console log from this server socket. i follow same process as socke.io doc.

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

3 Answers3

0

Since Socket.IO v3, you need to explicitly enable Cross-Origin Resource Sharing (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"
  }
});
Shashank
  • 31
  • 3
0

in client, inside useEffect instead of

socket = io(EP);

to this

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

0

In the browser, the WebSocket object does not support additional headers. In case you want to add some headers as part of some authentication mechanism, you can use the transportOptions attribute. Please note that in this case the headers won't be sent in the WebSocket upgrade request.

 // 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'
          }
        }
      }
    });

Credit: Engine.IO client