简体   繁体   English

将消息发送到node.js和socket.io中的单个套接字

[英]Sending a message to single socket in node.js and socket.io

How would one send a message out to a single socket using socket.io. 如何使用socket.io将消息发送到单个套接字。

I was thinking something like this but it doesn't work. 我在想像这样的东西,但是不起作用。

io.sockets.socket(socket.id).emit('messagetype', "message")

I get this error: 我收到此错误:

TypeError: Property 'connected' of object #<Namespace> is not a function

I think I'm just having an issue with syntax but can't find a source about it. 我认为我只是在语法上有一个问题,但找不到有关它的来源。

Basically this is what you need. 基本上这就是您所需要的。

io.on('connection', function(socket){
  socket.emit('messagetype', "message");
});

It's well documented at socketio-docs socketio-docs上有很好的记录

in your code you are usind to feth other persons socket but (socket.id) will always return your own socket id so you have to save others socket id in your database or in any array then you can send them any message: 在您的代码中,您可以使用其他套接字,但是(socket.id)将始终返回您自己的套接字ID,因此您必须将其他套接字ID保存在数据库或任何数组中,然后可以向他们发送任何消息:

   io.sockets.socket(socket_array['socketid']).emit('','');

here socket_array is an array where you have to save others socket id and 'socketid' is the key to feth the socketid;you can use username of others in stead of 'socketid', then it would be an unique id. 在这里,socket_array是一个数组,您必须在其中保存其他套接字ID,而'socketid'是用来保存套接字ID的键;您可以使用其他用户名代替'socketid',那么它将是唯一的ID。

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

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