7.5. websocket_server — websocket server module API

7.5.1. Class websocket_server

websocket_server.websocket_server_start(port, resource)

Initialize the websocket server to listen on a specific port.

  • port - the listening port of the server
  • resource - the resource of the server
websocket_server.websocket_server_send(message, length)

Send message to the client. Returns -1 if the websocket connection is closed and 0 if the connection is alive.

  • message - the message to send
  • length - the length of the message
websocket_server.websocket_server_receive(timeout)

Receive message from websocket. When the server receives a closing frame it sends a closing frame back to the client, stops automatically and raises a closing exception.

  • timeout - the time interval that receive blocks in order to receive the messsage
websocket_server.websocket_server_close()

Terminates the connection between the websocket server and the websocket client.

7.5.2. Example

import websocket_server
import time

PORT = 8088
TIMEOUT = 10000
RESOURCE = "/chat"

i=0

print("START WEBSOCKET SERVER")

ret = websocket_server.websocket_server_start(PORT,RESOURCE)

while i<5:

        try:
                msg=websocket_server.websocket_server_receive(TIMEOUT)
                print("RECEIVE FROM WEBSOCKET CLIENT: " + msg)
        except:
                print("Websocket is closed.")
                break;

        time.sleep(1000)

        result=websocket_server.websocket_server_send(msg,len(msg))
        if result<0:
                print("Websocket is closed.")
                break;

        print("SEND TO WEBSOCKET CLIENT: " + msg)
        i=i+1

if i==5:
        print("CLOSE WEBSOCKET SERVER")
        websocket_server.websocket_server_close()

while True:
        time.sleep(1000)