Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io connected always false

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?

like image 592
Anny Walker Avatar asked Nov 02 '18 02:11

Anny Walker


People also ask

Does Socket.IO reconnect automatically?

In the first case, the Socket will automatically try to reconnect, after a given delay.

How do you check if socket IO client is connected or not?

You can check the socket. connected property: var socket = io. connect(); console.

How do I remove a Socket.IO connection?

click(function(){ socket. disconnect(); }); It disconnects alright.


1 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();
});
like image 50
num8er Avatar answered Oct 10 '22 11:10

num8er