pythonwebsockettwistedubuntu-serverautobahn

Autobahn Python - onMessage event not called on server


I am quite new to python and websockets and I am creating a WebSocket server for a school project using Twisted and autobahn. I am testing this server using the html/javascript client from this Python chat example.

The server itself keeps a track of connected clients via a dictionary of key(sessionID):client. When a OnMessage() is called, I read the value, create a json, which I then send using Kafka for some other processing.

The server works fine on my localhost, using the Kafka on a Ubuntu Server provided by our school. However, after I tried to deploy this WebSocket server on the Ubuntu Server, I cant get the OnMessage() event to happen.

I get the OnOpen(), OnClose() event, but the OnMessage (OnMessageBegin aswell) event is never called, no matter what I do with the client/server.

I tried shutting down the firewall viac iptables and ufw, but to no success. Due to limitations with this server, only ports from range of 8000 to 9000 are open. Could this be an issue for autobahn/twisted when using websockets?

Here is the code I used for my WebSocket Server Protocol:

class MiddleServerProtocol(WebSocketServerProtocol):

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

def onOpen(self):
    identifier = uuid.uuid4()
    self.factory.register(self, identifier)
    logger.info("WebSocket connection open, Session ID: " + identifier)

def onMessageBegin(self, isBinary):
    super(MiddleServerProtocol, self).onMessageBegin(isBinary)


def onMessage(self, payload, is_binary):
    key = str(list(clients.keys())[list(clients.values()).index(self)])
    if is_binary:
        logger.error("Invalid message recieved: {0} bytes".
                     format(len(payload)) + " , Session ID: " + key)
    else:
        # SEND MESSAGE TO KAFKA
        message = prepare_message(payload, key).encode("utf-8")
        self.factory.producer_kafka.send(configLoad.
                                         get_value('TOPIC_SEND'),
                                         value=json.loads(message),
                                         key=key.encode('utf-8'))
        self.factory.producer_kafka.flush()
        logger.info("Json message received: " + message.
                    decode('cp1250') + " ,Session ID: " + key)

def onClose(self, was_clean, code, reason):
    key = str(list(clients.keys())[list(clients.values()).index(self)])
    logger.info("WebSocket connection closed: {0}".
                format(reason) + " , Session ID: " + key)

Here is the code I used for Websocket Server Factory:

class MiddleServerFactory(WebSocketServerFactory):

def __init__(self, *args, **kwargs):
    super(MiddleServerFactory, self).__init__(*args, **kwargs)
    self.producer_kafka = KafkaProducer(value_serializer=lambda v: json.dumps(v).encode('utf-8'),
                                        bootstrap_servers=configLoad.
                                        get_value('BOOTSTRAPSERVER'))
    logger.info(" Server successfully started.")

def register(self, client, identifier):
    """
   Add client to list of managed connections.
   We use generated ID as a unique identifier.
   """
    clients[identifier] = client

def unregister(self, identifier):
    """
   Remove client from list of managed connections.
   """
    del clients[identifier]

And here is how I run it:

factory = MiddleServerFactory(configLoad.get_value('URL'))
factory.protocol = MiddleServerProtocol
reactor.listenTCP(int(configLoad.get_value('PORT')), factory)
reactor.run()

Thanks for all the help and suggestions in advance.


Solution

  • To anyone still wondering:

    The issue with this one was that I wasn't using a HTTPS (WSS) communication between the server and the client, as the server itself was behind a proxy, which messed up the HTTP headers. To solve this, I had to switch to HTTPS (WSS) communication which apparently keeps the HTTP headers encrypted and the proxy doesn't mess with them.