4

How can we implement a private message system (client to client) using Websockets (and PHP)?

From what I understood, the server broadcasts the message and all of the clients can receive the message through connection.onmessage event handler. I was wondering if there is a way to send the message to only a targeted user in the websockets?

Philipp
  • 67,764
  • 9
  • 118
  • 153
Moe
  • 171
  • 2
  • 9
  • I have seen this http://stackoverflow.com/questions/14592513/websocket-message-to-specific-user , but there is no answer to that. – Moe Mar 18 '13 at 04:17

1 Answers1

9

When a client sends a messages (ws.send( message );) your WebSocket server will receive the message. The sockets that then you send that on to is determined entirely by your server code - your implementation.

To create a one-to-one chat you need a way of routing data between just the two clients involved in the chat. You also need a way of authenticating that only those two clients can receive that information.

WebSocket frameworks tend to provide an additional PubSub layer e.g. Pusher (who I previously worked for) do this using channels. You will find similar terminology along with 'subjects' and 'topics'.

Once you have a way of routing data (chat messages) between just two clients you then need to consider authenticating the subscription. More information can be found on that via this question which asks How do I create Private channel between two user. The question is about Ruby but is applicable to any technology.

leggetter
  • 15,248
  • 1
  • 55
  • 61
  • Thanks Leggetter. It seems implementing the solution using socket.io and node.js is easier. – Moe Mar 19 '13 at 05:38
  • socket.io isn't the only option and I'd recommend you have a look at alternatives. For PHP there's [Ratchet](http://socketo.me) and [Wrench](https://github.com/varspool/Wrench). However, they don't offer fallbacks when WebSockets are not present. If you are looking at node.js then have a look at [Faye](http://faye.jcoglan.com/). If you would like to stick with PHP and want connection fallbacks then Pusher is a good solution. – leggetter Mar 19 '13 at 10:23