Socket.io 连接总是假的

Ann*_*ker 5 javascript sockets node.js socket.io

我的socket.connected总是false,也不能发出或接收消息。

应用程序.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");
});
Run Code Online (Sandbox Code Playgroud)

服务器端

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

客户端

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();
    });
});
Run Code Online (Sandbox Code Playgroud)

没有收到任何“ on ” ,甚至没有收到错误”。那么我怎样才能让它工作呢?

num*_*8er 3

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

所以问题是你正在检查:.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();
});
Run Code Online (Sandbox Code Playgroud)