我的 socket.connected 始终为 false ,也无法发出或接收消息。


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


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


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

“上的”都不是收到的,甚至都不是“错误”。那么,我该如何运作呢?

最佳答案

我已经在本地检查了您的代码。

因此,问题在于您正在检查:.on('connection',...)何时应为.on('connect', ...)
因此,请尝试以下解决方法:

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

  console.log(socket.connected);

  load_posts();
});

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

10-06 04:01