socket.emit on sever side is ignored after connection?

有些话、适合烂在心里 提交于 2019-12-23 03:20:11

问题


I am trying to make my code function so that on a io connection, i have a socket.emit right afterwards which saves a variable from my server.js to a client.js.

Strangely, when I was working on a school desktop computer, the code was working perfectly fine, but once I transferred the files to my home desktop, the code did no function properly

When the code is run from my application, the console.log on client.js does not occur

Relevant code:

server.js

var http = require('http').Server(app); 
var path = require('path');  
var io = require('socket.io')(http);
var userLog = io.of('/logged');
userLog.on('connect', function(socket) {
// Send current user to client
socket.emit('saveUser', ({user:currentUser}))
console.log(currentUser + ' has connected');
}

client.js:

$(document).ready(function() {

   var me;
   socket.on('saveUser', function(data) {
    console.log(data)
    console.log(data[0])
    me = data.user;
    console.log("i am " + me);
   })
}

home.ejs

<script src="./socket.io/socket.io.js"></script>
<script>var socket = io('/logged');</script>
<script src="js/jquery.min.js"></script>
<script src="js/client.js"></script>

回答1:


Move the socket.on('saveUser', ...) outside the $(document).ready() and put it right after you establish the socket.io connection.

If the 'saveUser' message arrives before the document is ready, you will not have an event handler installed when the message arrives and you will miss it.



来源:https://stackoverflow.com/questions/49747656/socket-emit-on-sever-side-is-ignored-after-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!