Socket.io连接始终为假

时间:2018-11-02 02:58:20

标签: javascript node.js sockets socket.io

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

  

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

服务器端

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

没有收到,甚至没有收到错误。那请问我该如何运作呢?

1 个答案:

答案 0 :(得分:0)

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

问题是您正在检查:set()应该何时.on('connection',...)

因此,请尝试以下修复程序:

.on('connect', ...)