Socket.io connected always false

Viewed 10796

My socket.connected is always false, cannot emit or receive messages too.

app.js

var app = require('./config/server');    
var http = require('http').Server(app);
var io = require("socket.io")(http);

http.listen(80, function(err)
{
    console.log(err);
    console.log('Server client instagram_clone_v01 online');
});

io.sockets.on('connection', function (socket)
{
    console.log("new user connected");
});

server side

var sockets = io();
sockets.on('connection', function ()
{
    console.log("connected");
    sockets.emit("newPhoto");
});

client side

const socket = io.connect("http://localhost:80");
console.log(socket.connected);

socket.on('error', function()
{
    console.log("Sorry, there seems to be an issue with the connection!");
});

socket.on('connect_error', function(err)
{
    console.log("connect failed"+err);
});

socket.on('connection', function ()
{
    console.log("connected");
    socket.on('newPhoto',function()
    {
        load_posts();
    });
});

None of the "on"s are received, not even "error". So how can i make it work, please?

2 Answers

I've checked Your code locally.

So issue was that You're checking: .on('connection',...) when it should be .on('connect', ...)

So try this fix:

socket.on('connect', function() {
  console.log("Connected to WS server");

  console.log(socket.connected); 

  load_posts();
});

socket.on('newPhoto', function(){
  load_posts();
});

When I was building a basic socketio app using React frontend and Node Express backend, I came across a similar problem in v4. With the typical Node/React setup, your react app will live on port 3000 and your express server will live on port 5000, and according to the docs this results in you needing to set an open CORS policy to enable connections to the socketio server on port 5000.

Since Socket.IO v3, you need to explicitly enable Cross-Origin Resource Sharing (CORS). (docs)

I simply made sure my socketio definition was as such:

const app = express();
const httpServer = http.createServer(app);
const io = require("socket.io")(httpServer, {
  cors: {
    origin: "http://localhost:8080",
    methods: ["GET", "POST"]
  }
});

and I Was able to connect from a my react app inside of a useEffect. I was seeing all of the expected logs thereafter.

useEffect(() => {
    socket = io('localhost:5000');
    socket.on('connect', () => {
      console.log('socket connected');
      console.log(socket);
    });
  }, []);
Related