简体   繁体   English

Socket.IO 无法从服务器向客户端发送消息

[英]Socket.IO Can't emit message from serer to client

I have a connection with the server and client and have the server listening for a player to be made in the lobby.我与服务器和客户端建立了连接,并让服务器在大厅监听玩家。 The server receives the player name and updates the player, however, when emitting the player back to the client I am having issues.服务器接收播放器名称并更新播放器,但是,当将播放器发送回客户端时,我遇到了问题。

Simply, the pseudo-structure of our implementation follows as such...简单地说,我们实现的伪结构如下......

Server服务器

io.on('connection', function(socket){ ....
         socket.emit('ack', {....

         socket.on('createPlayer', function(data){
                          .... (update newPlayer object)  .....
                           socket.emit('newPlayer', {
                                         playerName: newPlayer.name
                              [...]

Client客户

let socket = io();

socket.on('ack', function(data) {
            console.log('ack', data)
} 

socket.on('newPlayer', function(data) {
              console.log('newPlayer', data)

When a connection is made by the client's browser to the server, the 'ack' message is sent and received and logged to the client's console.当客户端的浏览器与服务器建立连接时,会发送和接收“ack”消息并记录到客户端的控制台。 But, When the client makes a new player and the 'createPlayer' socket.on is hit it tries to emit the new player back to the client but is never received.但是,当客户端创建一个新播放器并且“createPlayer”socket.on 被击中时,它会尝试将新播放器发送回客户端,但从未收到。

Any suggestions as to why the client would never receive the sent message?关于为什么客户端永远不会收到发送的消息的任何建议?

You should use this for sending message to all connected clients:您应该使用它向所有连接的客户端发送消息:

io.emit('event_name', msg);

Also you should use this for all clients except new clients:此外,您应该将其用于除新客户端之外的所有客户端:

socket.broadcast.emit('event_name', msg);

This function is for sending message to new client that sent message at that time:此 function 用于向当时发送消息的新客户端发送消息:

socket.emit('event_name', msg)

You can send specified client using this method:您可以使用此方法发送指定的客户端:

io.to(socketId).emit('event_name', data)

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

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