How to send a message to a particular client with socket.io

前端 未结 6 1995
無奈伤痛
無奈伤痛 2020-11-28 00:02

I\'m starting with socket.io + node.js, I know how to send a message locally and to broadcast socket.broadcast.emit() function:- all the connected clients recei

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 00:52

    When a user connects, it should send a message to the server with a username which has to be unique, like an email.

    A pair of username and socket should be stored in an object like this:

    var users = {
        'userA@example.com': [socket object],
        'userB@example.com': [socket object],
        'userC@example.com': [socket object]
    }
    

    On the client, emit an object to the server with the following data:

    {
        to:[the other receiver's username as a string],
        from:[the person who sent the message as string],
        message:[the message to be sent as string]
    }
    

    On the server, listen for messages. When a message is received, emit the data to the receiver.

    users[data.to].emit('receivedMessage', data)
    

    On the client, listen for emits from the server called 'receivedMessage', and by reading the data you can handle who it came from and the message that was sent.

提交回复
热议问题