WebSocket-for-Python (ws4py)

0.6.0 · maintenance · verified Thu Apr 16

ws4py is a WebSocket client and server library for Python, supporting Python 3.6+ since version 0.6.0. It provides a straightforward API for building WebSocket applications, offering both threaded and eventlet/gevent-based server implementations. The library is currently in maintenance mode, with its last release (0.6.0) in 2021.

Common errors

Warnings

Install

Imports

Quickstart

A basic WebSocket client example using ws4py's threaded client. It connects to a server, sends a few messages, and closes. Note that a server must be running at `ws://localhost:9000/` for this client to successfully connect.

import time
from ws4py.client.threadedclient import WebSocketClient

class DummyClient(WebSocketClient):
    def opened(self):
        print("WebSocket opened. Sending messages...")
        for i in range(0, 5):
            self.send('Hello %d' % i)
            time.sleep(0.5)
        self.send('Bye')

    def closed(self, code, reason=None):
        print("WebSocket closed: %d %s" % (code, reason))

    def received_message(self, m):
        print("Received: %s" % m)
        if m.data == b'Bye':
            self.close()

# Note: This client expects a WebSocket server to be running at ws://localhost:9000/
# For a full runnable example, you'd also need a server like:
# from ws4py.server.wsgirefserver import WSGIServer, WebSocketWSGIRequestHandler
# from ws4py.websocket import WebSocket
# from threading import Thread
# class EchoWebSocket(WebSocket):
#    def received_message(self, message):
#        self.send(message.data, message.is_binary)
# server = WSGIServer(('localhost', 9000), WebSocketWSGIRequestHandler, websocket_class=EchoWebSocket)
# Thread(target=server.serve_forever).start()

if __name__ == '__main__':
    try:
        ws = DummyClient('ws://localhost:9000/', protocols=['http-only', 'chat'])
        ws.connect()
        ws.run_forever()
    except KeyboardInterrupt:
        ws.close()

view raw JSON →