【问题标题】:Socket.io connected always falseSocket.io 连接总是假的
【发布时间】:2019-04-06 07:36:19
【问题描述】:

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

没有一个“on收到,甚至没有“error”。那么,请问我怎样才能让它工作呢?

【问题讨论】:

  • 服务器端有消息吗?
  • 你在做console.log(socket.connected)之前没有等待socket.on('connection', ...)
  • 我认为这不能解释为什么 OP 没有收到连接或错误消息。
  • 不,console.log("connected");不显示

标签: javascript node.js sockets socket.io


【解决方案1】:

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

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

【讨论】:

  • 如果我将端口改为 3000 会怎样?顺便说一句,我正在使用 firefox 感谢您的快速回放:]
  • @AnnyWalker 你能把socket.on('connection', ...)改成socket.on('connect', ...)吗?
  • 刚刚尝试了“连接”和“连接”,对我不起作用,“连接”仍然是错误的。
  • @TerryWindwalker 将您的代码放在某处并与我分享
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 2023-03-18
  • 2015-03-28
相关资源
最近更新 更多