Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python WebSocket libraries open long-lived, two-way connections between a client and a server. A connection starts as an HTTP request and then carries messages in both directions until either side closes it. These libraries let chat apps, live dashboards, and AI agents stream data without polling.
Popularity
websockets has the most monthly downloads among the dedicated WebSocket libraries in this comparison, at 539.1M.
import asyncio
import aiohttp
async def main():
async with aiohttp.ClientSession() as session:
async with session.ws_connect('ws://localhost:8765') as ws:
await ws.send_str('hello')
asyncio.run(main())
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
sid = request.rel_url.query.get('clientId', '')
if sid:
# Reusing existing session, remove old self.sockets.pop(sid, None)
else:
sid = uuid.uuid4().hex
# Store WebSocket for backward compatibility self.sockets[sid] = ws
# Store metadata separately self.sockets_metadata[sid] = {"feature_flags": {}}
try:
# Send initial state to the new client await self.send("status", {"status": self.get_queue_info(), "sid": sid}, sid)
# On reconnect if we are the currently executing client send the current node if self.client_id == sid and self.last_node_id is not None:
await self.send("executing", { "node": self.last_node_id }, sid)
# Flag to track if we've received the first message first_message = True
async for msg in ws:
if msg.type == aiohttp.WSMsgType.ERROR:
logging.warning('ws connection closed with exception %s' % ws.exception())
elif msg.type == aiohttp.WSMsgType.TEXT:
try:
data = json.loads(msg.data)
# Check if first message is feature flags if first_message and data.get("type") == "feature_flags":
# Store client feature flags client_flags = data.get("data", {})
self.sockets_metadata[sid]["feature_flags"] = client_flags
# Send server feature flags in response await self.send(
"feature_flags",
feature_flags.get_server_features(),
sid,
)
logging.debug(
f"Feature flags negotiated for client {sid}: {client_flags}"
)
first_message = False
except json.JSONDecodeError:
logging.warning(
f"Invalid JSON received from client {sid}: {msg.data}"
)
except Exception as e:
logging.error(f"Error processing WebSocket message: {e}")
finally:
self.sockets.pop(sid, None)
self.sockets_metadata.pop(sid, None)
return ws
websockets
Builds WebSocket servers and clients in Python.
Downloads / mo
539.1M
Stars
5.7K
Last release
17.4
License
BSD-3-Clause
Strengths
Offers async and threaded interfaces.Choose a coroutine-based or threaded connection API for the application.
Retries transient connection failures.Use the asynchronous connect iterator for reconnects with exponential backoff.
Limitations
Receives must stay serialized.Have one coroutine receive messages from each connection at a time.
Directly awaited connections need closing.Close a directly awaited connection when the application finishes using it.
def send_keepalive_ping(self) -> None:
self.ping_timer = None
if self.close_sent or self.transport.is_closing(): # pragma: no cover
return
# Random 4-byte payload identifies this ping; `handle_pong` uses it to ignore stale or unsolicited pongs. # See https://github.com/python-websockets/websockets/blob/4d229bf9f583d593aa103287aee0a77c9fbc3a79/src/websockets/asyncio/connection.py#L624 self.pending_ping_payload = struct.pack("!I", random.getrandbits(32))
self.ping_sent_at = self.loop.time()
self.conn.send_ping(self.pending_ping_payload)
self.transport.write(b"".join(self.conn.data_to_send()))
if self.ping_timeout is not None:
self.pong_timer = self.loop.call_later(self.ping_timeout, self.keepalive_timeout)
else: # pragma: no cover
self.schedule_ping()
websocket-client
Provides low-level WebSocket client APIs and callback-based long-lived connections.
Downloads / mo
185.6M
Stars
3.7K
Last release
1.9.2
License
Apache-2.0
Strengths
Handles long-lived callback connections.Attach message, error, and close callbacks to WebSocketApp.
Reconnects through its built-in dispatcher.Set a reconnect delay on run_forever for automatic retries.
Limitations
Compression needs a different client.Choose another client when the peer requires permessage-deflate.
Asyncio needs another integration.Choose a native asyncio client for coroutine-based applications.
def create_websocket(configuration, url, headers=None):
enableTrace(False)
# We just need to pass the Authorization, ignore all the other # http headers we get from the generated code header = []
if headers and 'authorization' in headers:
header.append("authorization: %s" % headers['authorization'])
if headers and 'sec-websocket-protocol' in headers:
header.append("sec-websocket-protocol: %s" %
headers['sec-websocket-protocol'])
else:
header.append("sec-websocket-protocol: %s,%s" % (V5_CHANNEL_PROTOCOL, V4_CHANNEL_PROTOCOL))
if url.startswith('wss://') and configuration.verify_ssl:
ssl_opts = {
'cert_reqs': ssl.CERT_REQUIRED,
'ca_certs': configuration.ssl_ca_cert or certifi.where(),
}
if configuration.assert_hostname is not None:
ssl_opts['check_hostname'] = configuration.assert_hostname
else:
ssl_opts = {'cert_reqs': ssl.CERT_NONE}
if configuration.cert_file:
ssl_opts['certfile'] = configuration.cert_file
if configuration.key_file:
ssl_opts['keyfile'] = configuration.key_file
if configuration.tls_server_name:
ssl_opts['server_hostname'] = configuration.tls_server_name
websocket = WebSocket(sslopt=ssl_opts, skip_utf8_validation=False)
connect_opt = {
'header': header
}
if configuration.proxy or configuration.proxy_headers:
connect_opt = websocket_proxycare(connect_opt, configuration, url, headers)
websocket.connect(url, **connect_opt)
return websocket
Tornado
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
def send_ping(self):
"""send a ping to keep the websocket alive"""
if self.ws_connection is None and self.ping_callback is not None:
self.ping_callback.stop()
return
if self.ws_connection.client_terminated:
self.close()
return
# check for timeout on pong. Make sure that we really have sent a recent ping in # case the machine with both server and client has been suspended since the last ping. now = ioloop.IOLoop.current().time()
since_last_pong = 1e3 * (now - self.last_pong)
since_last_ping = 1e3 * (now - self.last_ping)
if since_last_ping < 2 * self.ping_interval and since_last_pong > self.ping_timeout:
self.log.warning("WebSocket ping timeout after %i ms.", since_last_pong)
self.close()
return
self.ping(b"")
self.last_ping = now
wsproto
Implements WebSocket protocol state and frame handling without owning network I/O.
Downloads / mo
74.9M
Stars
303
Last release
1.3.2
License
MIT
Strengths
Fits custom network transports.Embed the protocol state machine in the application’s own transport.
Supports client and server roles.Use the same protocol class for either end of a WebSocket connection.
Limitations
Network I/O stays application-owned.Provide the code that reads and writes bytes on the actual connection.
async def execute(self, cmd: Generator[dict, T, Any]) -> T:
"""Execute a command on the server and wait for the result.
Args:
cmd: any CDP command
Returns:
a CDP result
"""
cmd_id = next(self.id_iter)
cmd_event = trio.Event()
self.inflight_cmd[cmd_id] = cmd, cmd_event
request = next(cmd)
request["id"] = cmd_id
if self.session_id:
request["sessionId"] = self.session_id
request_str = json.dumps(request)
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f"Sending CDP message: {cmd_id} {cmd_event}: {request_str}")
try:
await self.ws.send_message(request_str)
except WsConnectionClosed as wcc:
raise CdpConnectionClosed(wcc.reason) from None
await cmd_event.wait()
response = self.inflight_result.pop(cmd_id)
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f"Received CDP message: {response}")
if isinstance(response, Exception):
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f"Exception raised by {cmd_event} message: {type(response).__name__}")
raise response
return response
FAQ
websockets suits servers and clients that use asyncio or threads. websocket-client suits callback-based client connections outside asyncio. wsproto suits custom transports that own their network I/O.
websockets builds WebSocket servers and clients with coroutine-based or threaded APIs. Only one coroutine at a time should receive messages from each connection.
Its asynchronous connect iterator retries transient connection failures with exponential backoff.
websocket-client provides low-level WebSocket client APIs and callback-based long-lived connections. Applications built on asyncio need a native asyncio client instead.
For coding agents
Found your WebSocket library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.