2

I've a server as follow:-

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

The above code receives the message and replies back with the same message. However, my use case is different.

I'm processing some data, storing it into the DB and then finally want to send the data to the connected clients, or one type of data to specific set of connected clients and the other type to another.

How can I do it? How can I call sendMessage function outside the class?

Praful Bagai
  • 16,684
  • 50
  • 136
  • 267

2 Answers2

1

You need to subclass WebSocketServerFactory to keep track of your connections.

Take a look at this example, which stores all the open connections in a list and broadcasts to all of them. You could easily adapt it to send specific messages to certain clients.

Henry Heath
  • 1,072
  • 11
  • 19
  • Thanks @Henry for the response. While I was playing around with the code, I stumbled upon 2 situations(doubts). 1) Consider a situation where I've an API endpoint which saves data in DB. In `post_save` signal (Django), I want to broadcast the dat to the connected clients. How can I do it? `2)` Why are there 2 ports, ie `9000` & `8080`? – Praful Bagai Jul 06 '17 at 13:56
  • Is the API endpoint a websockets endpoint or an HTTP endpoint on the Django app? Is saving data triggered by a websockets message or an HTTP request? – Henry Heath Jul 06 '17 at 17:42
  • Any thoughts on it, Henry? – Praful Bagai Jul 07 '17 at 06:28
  • You have two services: an HTTP service and a websockets service. When a certain HTTP request comes in you want to update the DB then broadcast to the websockets clients. One possible flow would be for the HTTP service to create a websockets connection, send a message that triggers the websockets service to do a broadcast. – Henry Heath Jul 07 '17 at 09:13
0

Are you sure you don't want to just use WAMP instead of raw WebSockets?

This might be a lot easier for your use-case, as "broadcast information to interested clients" is exactly what the Publish/Subscribe pattern is for.

meejah
  • 316
  • 1
  • 5