简体   繁体   English

Socket.io未从客户端向服务器发送数据

[英]Socket.io not sending data from client to server

I seem to be having a problem with communication from the client to the server using socket.io. 我似乎在使用socket.io从客户端到服务器的通讯出现问题。

First, the JSON object I am sending 首先,我要发送的JSON对象

loginInfo = { email: 'username', password: 'password' }

On the client side I have: 在客户端,我有:

socket.emit('user:login', loginInfo);

Then on the server side I have 然后在服务器端

socket.on('user:login', function(loginInfo) {
    console.log('data being sent is:\n' + loginInfo);
});

This prints out in the console: 这会在控制台中打印出来:

data being sent is:
function ack() {
    self.log.debug('sending data ack packet');
    socket.packet({
        type: 'ack'
      , args: util.toArray(arguments)
      , ackId: packet.id
    });
}

Similarly if i do 同样,如果我这样做

socket.on('user:login', function(loginInfo) {
    console.log('data being sent is:\n' + loginInfo.password);
});

The console prints out: 控制台将输出:

data being sent is:
undefined

I have used socket.io in the past, and have never run into this issue before, so I must be doing something weird. 我过去曾经使用过socket.io,并且以前从未遇到过此问题,因此我必须做一些奇怪的事情。 If anyone knows the cause of this problem I'd be extremely grateful for insight on how to fix this issue. 如果有人知道导致此问题的原因,我将非常感谢您提供有关如何解决此问题的见解。

Edit: The problem does not have to do with what is printing out, I was just using that to illustrate my problem, which is that the loginInfo JSON is either not being sent by the client properly or not being received by the server properly. 编辑:问题与打印出来的内容无关,我只是用它来说明我的问题,这是客户端未正确发送loginInfo JSON或服务器未正确接收到loginInfo JSON。 My goal is to have the loginInfo be received by the server so I can process the data. 我的目标是让loginInfo被服务器接收,以便我可以处理数据。

Thanks! 谢谢!

Try making the array a property of an object... for whatever reason that worked for me; 尝试使数组成为对象的属性……无论出于何种原因对我有用;

messageIds = [1,2,3,4,5,6];

This did not work: 这不起作用:

socket.emit('updateMessage',JSON.stringify(messageIds));

This did work: 这确实有效:

  socket.emit('updateMessage',{1:messageIds});

Weird bug, not sure why. 奇怪的错误,不确定为什么。

您需要对对象进行字符串化以将其附加到字符串,否则行为将无法预测:

console.log('data being sent is:\n' + JSON.stringify(loginInfo));

Is there a possibility that you have a function called loginInfo on the client side? 客户端是否可能有一个名为loginInfo的函数? I believe the socket.emit('user:login', loginInfo); 我相信socket.emit('user:login', loginInfo); line is sending a function instead of a parameter. 行正在发送函数而不是参数。 A function as a parameter in socket.emit is used for getting acknowledgements. socket.emit作为参数的函数用于获取确认。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM