API¶
Design¶
websockets provides complete client and server implementations, as shown
in the getting started guide. These functions are built on top
of low-level APIs reflecting the two phases of the WebSocket protocol:
An opening handshake, in the form of an HTTP Upgrade request;
Data transfer, as framed messages, ending with a closing handshake.
The first phase is designed to integrate with existing HTTP software.
websockets provides functions to build and validate the request and
response headers.
The second phase is the core of the WebSocket protocol. websockets
provides a standalone implementation on top of asyncio with a very simple
API.
For convenience, public APIs can be imported directly from the
websockets package, unless noted otherwise. Anything that isn’t listed
in this document is a private API.
High-level¶
Server¶
The websockets.server module defines a simple WebSocket server API.
- websockets.server.serve(ws_handler, host=None, port=None, *, create_protocol=None, timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16, loop=None, origins=None, extensions=None, subprotocols=None, extra_headers=None, compression='deflate', **kwds)[source]¶
Create, start, and return a
WebSocketServer.serve()returns an awaitable. Awaiting it yields an instance ofWebSocketServerwhich providesclose()andwait_closed()methods for terminating the server and cleaning up its resources.On Python ≥ 3.5,
serve()can also be used as an asynchronous context manager. In this case, the server is shut down when exiting the context.serve()is a wrapper around the event loop’screate_server()method. Internally, it creates and starts aServerobject by callingcreate_server(). TheWebSocketServerit returns keeps a reference to this object.The
ws_handlerargument is the WebSocket handler. It must be a coroutine accepting two arguments: aWebSocketServerProtocoland the request URI.The
hostandportarguments, as well as unrecognized keyword arguments, are passed along tocreate_server(). For example, you can set thesslkeyword argument to aSSLContextto enable TLS.The
create_protocolparameter allows customizing the asyncio protocol that manages the connection. It should be a callable or class accepting the same arguments asWebSocketServerProtocoland returning aWebSocketServerProtocolinstance. It defaults toWebSocketServerProtocol.The behavior of the
timeout,max_size, andmax_queue,read_limit, andwrite_limitoptional arguments is described in the documentation ofWebSocketCommonProtocol.serve()also accepts the following optional arguments:originsdefines acceptable Origin HTTP headers — include''if the lack of an origin is acceptableextensionsis a list of supported extensions in order of decreasing preferencesubprotocolsis a list of supported subprotocols in order of decreasing preferenceextra_headerssets additional HTTP response headers — it can be aHeadersinstance, aMapping, an iterable of(name, value)pairs, or a callable taking the request path and headers in arguments and returning one of the above.compressionis a shortcut to configure compression extensions; by default it enables the “permessage-deflate” extension; set it toNoneto disable compression
Whenever a client connects, the server accepts the connection, creates a
WebSocketServerProtocol, performs the opening handshake, and delegates to the WebSocket handler. Once the handler completes, the server performs the closing handshake and closes the connection.When a server is closed with
close(), all running WebSocket handlers are cancelled. They may interceptCancelledErrorand perform cleanup actions before re-raising that exception. If a handler started new tasks, it should cancel them as well in that case.Since there’s no useful way to propagate exceptions triggered in handlers, they’re sent to the
'websockets.server'logger instead. Debugging is much easier if you configure logging to print them:import logging logger = logging.getLogger('websockets.server') logger.setLevel(logging.ERROR) logger.addHandler(logging.StreamHandler())
- websockets.server.unix_serve(ws_handler, path, *, create_protocol=None, timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16, loop=None, origins=None, extensions=None, subprotocols=None, extra_headers=None, compression='deflate', **kwds)[source]¶
Similar to
serve(), but for listening on Unix sockets.This function calls the event loop’s
create_unix_server()method.It is only available on Unix.
It’s useful for deploying a server behind a reverse proxy such as nginx.
- class websockets.server.WebSocketServer(loop)[source]¶
Wrapper for
Serverthat closes connections on exit.This class provides the return type of
serve().It mimics the interface of
AbstractServer, namely itsclose()andwait_closed()methods, to close WebSocket connections properly on exit, in addition to closing the underlyingServer.Instances of this class store a reference to the
Serverobject returned bycreate_server()rather than inherit fromServerin part becausecreate_server()doesn’t support passing a customServerclass.- close()[source]¶
Close the underlying server, and clean up connections.
This calls
close()on the underlyingServerobject, closes open connections with status code 1001, and stops accepting new connections.
- wait_closed()[source]¶
Wait until the underlying server and all connections are closed.
This calls
wait_closed()on the underlyingServerobject and waits until closing handshakes are complete and all connections are closed.This method must be called after
close().
- class websockets.server.WebSocketServerProtocol(ws_handler, ws_server, *, host=None, port=None, secure=None, timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16, loop=None, origins=None, extensions=None, subprotocols=None, extra_headers=None)[source]¶
Complete WebSocket server implementation as an
asyncio.Protocol.This class inherits most of its methods from
WebSocketCommonProtocol.For the sake of simplicity, it doesn’t rely on a full HTTP implementation. Its support for HTTP responses is very limited.
- handshake(origins=None, available_extensions=None, available_subprotocols=None, extra_headers=None)[source]¶
Perform the server side of the opening handshake.
If provided,
originsis a list of acceptable HTTP Origin values. Include''if the lack of an origin is acceptable.If provided,
available_extensionsis a list of supported extensions in the order in which they should be used.If provided,
available_subprotocolsis a list of supported subprotocols in order of decreasing preference.If provided,
extra_headerssets additional HTTP response headers. It can be aHeadersinstance, aMapping, an iterable of(name, value)pairs, or a callable taking the request path and headers in arguments and returning one of the above.Raise
InvalidHandshakeif the handshake fails.Return the path of the URI of the request.
- process_request(path, request_headers)[source]¶
Intercept the HTTP request and return an HTTP response if needed.
request_headersis aHeadersinstance.If this coroutine returns
None, the WebSocket handshake continues. If it returns a status code, headers and a response body, that HTTP response is sent and the connection is closed.The HTTP status must be a
HTTPStatus. (HTTPStatuswas added in Python 3.5. Use a compatible object on earlier versions. Look atSWITCHING_PROTOCOLSinwebsockets.compatibilityfor an example.)HTTP headers must be a
Headersinstance, aMapping, or an iterable of(name, value)pairs.The HTTP response body must be
bytes. It may be empty.This method may be overridden to check the request headers and set a different status, for example to authenticate the request and return
HTTPStatus.UNAUTHORIZEDorHTTPStatus.FORBIDDEN.It is declared as a coroutine because such authentication checks are likely to require network requests.
- static select_subprotocol(client_subprotocols, server_subprotocols)[source]¶
Pick a subprotocol among those offered by the client.
If several subprotocols are supported by the client and the server, the default implementation selects the preferred subprotocols by giving equal value to the priorities of the client and the server.
If no subprotocols are supported by the client and the server, it proceeds without a subprotocol.
This is unlikely to be the most useful implementation in practice, as many servers providing a subprotocol will require that the client uses that subprotocol. Such rules can be implemented in a subclass.
Client¶
The websockets.client module defines a simple WebSocket client API.
- websockets.client.connect(uri, *, create_protocol=None, timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16, loop=None, origin=None, extensions=None, subprotocols=None, extra_headers=None, compression='deflate', **kwds)[source]¶
Connect to the WebSocket server at the given
uri.connect()returns an awaitable. Awaiting it yields an instance ofWebSocketClientProtocolwhich can then be used to send and receive messages.On Python ≥ 3.5.1,
connect()can be used as a asynchronous context manager. In that case, the connection is closed when exiting the context.connect()is a wrapper around the event loop’screate_connection()method. Unknown keyword arguments are passed tocreate_connection().For example, you can set the
sslkeyword argument to aSSLContextto enforce some TLS settings. When connecting to awss://URI, if this argument isn’t provided explicitly, it’s set toTrue, which means Python’s defaultSSLContextis used.The behavior of the
timeout,max_size, andmax_queue,read_limit, andwrite_limitoptional arguments is described in the documentation ofWebSocketCommonProtocol.The
create_protocolparameter allows customizing the asyncio protocol that manages the connection. It should be a callable or class accepting the same arguments asWebSocketClientProtocoland returning aWebSocketClientProtocolinstance. It defaults toWebSocketClientProtocol.connect()also accepts the following optional arguments:originsets the Origin HTTP headerextensionsis a list of supported extensions in order of decreasing preferencesubprotocolsis a list of supported subprotocols in order of decreasing preferenceextra_headerssets additional HTTP request headers – it can be aHeadersinstance, aMapping, or an iterable of(name, value)pairscompressionis a shortcut to configure compression extensions; by default it enables the “permessage-deflate” extension; set it toNoneto disable compression
connect()raisesInvalidURIifuriis invalid andInvalidHandshakeif the opening handshake fails.
- class websockets.client.WebSocketClientProtocol(*, host=None, port=None, secure=None, timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16, loop=None, origin=None, extensions=None, subprotocols=None, extra_headers=None)[source]¶
Complete WebSocket client implementation as an
asyncio.Protocol.This class inherits most of its methods from
WebSocketCommonProtocol.- handshake(wsuri, origin=None, available_extensions=None, available_subprotocols=None, extra_headers=None)[source]¶
Perform the client side of the opening handshake.
If provided,
originsets the Origin HTTP header.If provided,
available_extensionsis a list of supported extensions in the order in which they should be used.If provided,
available_subprotocolsis a list of supported subprotocols in order of decreasing preference.If provided,
extra_headerssets additional HTTP request headers. It must be aHeadersinstance, aMapping, or an iterable of(name, value)pairs.Raise
InvalidHandshakeif the handshake fails.
Shared¶
The websockets.protocol module handles WebSocket control and data
frames as specified in sections 4 to 8 of RFC 6455.
- class websockets.protocol.WebSocketCommonProtocol(*, host=None, port=None, secure=None, timeout=10, max_size=2**20, max_queue=2**5, read_limit=2**16, write_limit=2**16, loop=None)[source]¶
This class implements common parts of the WebSocket protocol.
It assumes that the WebSocket connection is established. The handshake is managed in subclasses such as
WebSocketServerProtocolandWebSocketClientProtocol.It runs a task that stores incoming data frames in a queue and deals with control frames automatically. It sends outgoing data frames and performs the closing handshake.
On Python ≥ 3.6,
WebSocketCommonProtocolinstances support asynchronous iteration:async for message in websocket: await process(message)
The iterator yields incoming messages. It exits normally when the connection is closed with the status code 1000 (OK) or 1001 (going away). It raises a
ConnectionClosedexception when the connection is closed with any other status code.The
host,portandsecureparameters are simply stored as attributes for handlers that need them.The
timeoutparameter defines the maximum wait time in seconds for completing the closing handshake and, only on the client side, for terminating the TCP connection.close()will complete in at most4 * timeouton the server side and5 * timeouton the client side.The
max_sizeparameter enforces the maximum size for incoming messages in bytes. The default value is 1MB.Nonedisables the limit. If a message larger than the maximum size is received,recv()will raiseConnectionClosedand the connection will be closed with status code 1009.The
max_queueparameter sets the maximum length of the queue that holds incoming messages. The default value is 32. 0 disables the limit. Messages are added to an in-memory queue when they’re received; thenrecv()pops from that queue. In order to prevent excessive memory consumption when messages are received faster than they can be processed, the queue must be bounded. If the queue fills up, the protocol stops processing incoming data untilrecv()is called. In this situation, various receive buffers (at least inasyncioand in the OS) will fill up, then the TCP receive window will shrink, slowing down transmission to avoid packet loss.Since Python can use up to 4 bytes of memory to represent a single character, each websocket connection may use up to
4 * max_size * max_queuebytes of memory to store incoming messages. By default, this is 128MB. You may want to lower the limits, depending on your application’s requirements.The
read_limitargument sets the high-water limit of the buffer for incoming bytes. The low-water limit is half the high-water limit. The default value is 64kB, half of asyncio’s default (based on the current implementation ofStreamReader).The
write_limitargument sets the high-water limit of the buffer for outgoing bytes. The low-water limit is a quarter of the high-water limit. The default value is 64kB, equal to asyncio’s default (based on the current implementation ofFlowControlMixin).As soon as the HTTP request and response in the opening handshake are processed:
the request path is available in the
pathattribute;the request and response HTTP headers are available in the
request_headersandresponse_headersattributes, which areHeadersinstances.
These attributes must be treated as immutable.
If a subprotocol was negotiated, it’s available in the
subprotocolattribute.Once the connection is closed, the status code is available in the
close_codeattribute and the reason inclose_reason.- close(code=1000, reason='')[source]¶
This coroutine performs the closing handshake.
It waits for the other end to complete the handshake and for the TCP connection to terminate.
It doesn’t do anything once the connection is closed. In other words it’s idemptotent.
It’s safe to wrap this coroutine in
ensure_future()since errors during connection termination aren’t particularly useful.
- recv()[source]¶
This coroutine receives the next message.
It returns a
strfor a text frame andbytesfor a binary frame.When the end of the message stream is reached,
recv()raisesConnectionClosed. This can happen after a normal connection closure, a protocol error or a network failure.Changed in version 3.0:
recv()used to returnNoneinstead. Refer to the changelog for details.
- send(data)[source]¶
This coroutine sends a message.
It sends
stras a text frame andbytesas a binary frame. It raises aTypeErrorfor other inputs.
- ping(data=None)[source]¶
This coroutine sends a ping.
It returns a
Futurewhich will be completed when the corresponding pong is received and which you may ignore if you don’t want to wait.A ping may serve as a keepalive or as a check that the remote endpoint received all messages up to this point:
pong_waiter = await ws.ping() await pong_waiter # only if you want to wait for the pong
By default, the ping contains four random bytes. The content may be overridden with the optional
dataargument which must be of typestr(which will be encoded to UTF-8) orbytes.
- pong(data=b'')[source]¶
This coroutine sends a pong.
An unsolicited pong may serve as a unidirectional heartbeat.
The content may be overridden with the optional
dataargument which must be of typestr(which will be encoded to UTF-8) orbytes.
- local_address¶
Local address of the connection.
This is a
(host, port)tuple orNoneif the connection hasn’t been established yet.
- remote_address¶
Remote address of the connection.
This is a
(host, port)tuple orNoneif the connection hasn’t been established yet.
- open¶
This property is
Truewhen the connection is usable.It may be used to detect disconnections but this is discouraged per the EAFP principle. When
openisFalse, using the connection raises aConnectionClosedexception.
Exceptions¶
- exception websockets.exceptions.AbortHandshake(status, headers, body=b'')[source]¶
Exception raised to abort a handshake and return a HTTP response.
- exception websockets.exceptions.ConnectionClosed(code, reason)[source]¶
Exception raised when trying to read or write on a closed connection.
Provides the connection close code and reason in its
codeandreasonattributes respectively.
- exception websockets.exceptions.DuplicateParameter(name)[source]¶
Exception raised when a parameter name is repeated in an extension header.
- exception websockets.exceptions.InvalidHandshake[source]¶
Exception raised when a handshake request or response is invalid.
- exception websockets.exceptions.InvalidHeader(name, value)[source]¶
Exception raised when a HTTP header doesn’t have a valid format or value.
- exception websockets.exceptions.InvalidHeaderFormat(name, error, string, pos)[source]¶
Exception raised when a Sec-WebSocket-* HTTP header cannot be parsed.
- exception websockets.exceptions.InvalidHeaderValue(name, value)[source]¶
Exception raised when a Sec-WebSocket-* HTTP header has a wrong value.
- exception websockets.exceptions.InvalidMessage[source]¶
Exception raised when the HTTP message in a handshake request is malformed.
- exception websockets.exceptions.InvalidOrigin(origin)[source]¶
Exception raised when the Origin header in a request isn’t allowed.
- exception websockets.exceptions.InvalidParameterName(name)[source]¶
Exception raised when a parameter name in an extension header is invalid.
- exception websockets.exceptions.InvalidParameterValue(name, value)[source]¶
Exception raised when a parameter value in an extension header is invalid.
- exception websockets.exceptions.InvalidState[source]¶
Exception raised when an operation is forbidden in the current state.
- exception websockets.exceptions.InvalidStatusCode(status_code)[source]¶
Exception raised when a handshake response status code is invalid.
Provides the integer status code in its
status_codeattribute.
- exception websockets.exceptions.InvalidURI[source]¶
Exception raised when an URI isn’t a valid websocket URI.
- exception websockets.exceptions.InvalidUpgrade(name, value)[source]¶
Exception raised when a Upgrade or Connection header isn’t correct.
- exception websockets.exceptions.NegotiationError[source]¶
Exception raised when negociating an extension fails.
Low-level¶
Opening handshake¶
The websockets.handshake module deals with the WebSocket opening
handshake according to section 4 of RFC 6455.
Functions defined in this module manipulate HTTP headers. The headers
argument must implement get and __setitem__ and get — a small
subset of the MutableMapping abstract base class.
Headers names and values are str objects containing only ASCII
characters.
Some checks cannot be performed because they depend too much on the context; instead, they’re documented below.
To accept a connection, a server must:
Read the request, check that the method is GET, and check the headers with
check_request(),Send a 101 response to the client with the headers created by
build_response()if the request is valid; otherwise, send an appropriate HTTP error code.
To open a connection, a client must:
Send a GET request to the server with the headers created by
build_request(),Read the response, check that the status code is 101, and check the headers with
check_response().
- websockets.handshake.build_request(headers)[source]¶
Build a handshake request to send to the server.
Return the
keywhich must be passed tocheck_response().
- websockets.handshake.build_response(headers, key)[source]¶
Build a handshake response to send to the client.
keycomes fromcheck_request().
- websockets.handshake.check_request(headers)[source]¶
Check a handshake request received from the client.
If the handshake is valid, this function returns the
keywhich must be passed tobuild_response().Otherwise it raises an
InvalidHandshakeexception and the server must return an error like 400 Bad Request.This function doesn’t verify that the request is an HTTP/1.1 or higher GET request and doesn’t perform Host and Origin checks. These controls are usually performed earlier in the HTTP request handling code. They’re the responsibility of the caller.
- websockets.handshake.check_response(headers, key)[source]¶
Check a handshake response received from the server.
keycomes frombuild_request().If the handshake is valid, this function returns
None.Otherwise it raises an
InvalidHandshakeexception.This function doesn’t verify that the response is an HTTP/1.1 or higher response with a 101 status code. These controls are the responsibility of the caller.
Data transfer¶
The websockets.framing module implements data framing as specified in
section 5 of RFC 6455.
It deals with a single frame at a time. Anything that depends on the sequence
of frames is implemented in websockets.protocol.
- class websockets.framing.Frame(fin, opcode, data, rsv1=False, rsv2=False, rsv3=False)[source]¶
WebSocket frame.
finis the FIN bitrsv1is the RSV1 bitrsv2is the RSV2 bitrsv3is the RSV3 bitopcodeis the opcodedatais the payload data
Only these fields are needed by higher level code. The MASK bit, payload length and masking-key are handled on the fly by
read()andwrite().- check()[source]¶
Check that this frame contains acceptable values.
Raise
WebSocketProtocolErrorif this frame contains incorrect values.
- classmethod read(reader, *, mask, max_size=None, extensions=None)[source]¶
Read a WebSocket frame and return a
Frameobject.readeris a coroutine taking an integer argument and reading exactly this number of bytes, unless the end of file is reached.maskis abooltelling whether the frame should be masked i.e. whether the read happens on the server side.If
max_sizeis set and the payload exceeds this size in bytes,PayloadTooBigis raised.If
extensionsis provided, it’s a list of classes with andecode()method that transform the frame and return a new frame. They are applied in reverse order.This function validates the frame before returning it and raises
WebSocketProtocolErrorif it contains incorrect values.
- write(writer, *, mask, extensions=None)[source]¶
Write a WebSocket frame.
frameis theFrameobject to write.writeris a function accepting bytes.maskis abooltelling whether the frame should be masked i.e. whether the write happens on the client side.If
extensionsis provided, it’s a list of classes with anencode()method that transform the frame and return a new frame. They are applied in order.This function validates the frame before sending it and raises
WebSocketProtocolErrorif it contains incorrect values.
- websockets.framing.encode_data(data)[source]¶
Helper that converts
strorbytestobytes.strare encoded with UTF-8.
- websockets.framing.parse_close(data)[source]¶
Parse the data in a close frame.
Return
(code, reason)whencodeis anintandreasonastr.Raise
WebSocketProtocolErrororUnicodeDecodeErrorif the data is invalid.
- websockets.framing.serialize_close(code, reason)[source]¶
Serialize the data for a close frame.
This is the reverse of
parse_close().
URI parser¶
The websockets.uri module implements parsing of WebSocket URIs
according to section 3 of RFC 6455.
- class websockets.uri.WebSocketURI(secure, host, port, resource_name, user_info)¶
WebSocket URI.
secureis the secure flaghostis the lower-case hostportif the integer port, it’s always provided even if it’s the defaultresource_nameis the resource name, that is, the path and optional queryuser_infois an(username, password)tuple when the URI contains User Information, elseNone.
- property host¶
Alias for field number 1
- property port¶
Alias for field number 2
- property resource_name¶
Alias for field number 3
- property secure¶
Alias for field number 0
- property user_info¶
Alias for field number 4
- websockets.uri.parse_uri(uri)[source]¶
This function parses and validates a WebSocket URI.
If the URI is valid, it returns a
WebSocketURI.Otherwise it raises an
InvalidURIexception.
Utilities¶
The websockets.headers module provides parsers and serializers for HTTP
headers used in WebSocket handshake messages.
Its functions cannot be imported from websockets. They must be imported
from websockets.headers.
- websockets.headers.build_extension_list(extensions)[source]¶
Unparse a
Sec-WebSocket-Extensionsheader.This is the reverse of
parse_extension_list().
- websockets.headers.build_subprotocol_list(protocols)[source]¶
Unparse a
Sec-WebSocket-Protocolheader.This is the reverse of
parse_subprotocol_list().
- websockets.headers.parse_connection(string)[source]¶
Parse a
Connectionheader.Return a list of connection options.
Raise
InvalidHeaderFormaton invalid inputs.
- websockets.headers.parse_extension_list(string)[source]¶
Parse a
Sec-WebSocket-Extensionsheader.Return a value with the following format:
[ ( 'extension name', [ ('parameter name', 'parameter value'), .... ] ), ... ]
Parameter values are
Nonewhen no value is provided.Raise
InvalidHeaderFormaton invalid inputs.
- websockets.headers.parse_subprotocol_list(string)[source]¶
Parse a
Sec-WebSocket-Protocolheader.Raise
InvalidHeaderFormaton invalid inputs.
- websockets.headers.parse_upgrade(string)[source]¶
Parse an
Upgradeheader.Return a list of connection options.
Raise
InvalidHeaderFormaton invalid inputs.
The websockets.http module provides basic HTTP parsing and
serialization. It is merely adequate for WebSocket handshake messages.
Its functions cannot be imported from websockets. They must be imported
from websockets.http.
- class websockets.http.Headers(*args, **kwargs)[source]¶
Data structure for working with HTTP headers efficiently.
A
listof(name, values)is inefficient for lookups.A
dictdoesn’t suffice because header names are case-insensitive and multiple occurrences of headers with the same name are possible.Headersstores HTTP headers in a hybrid data structure to provide efficient insertions and lookups while preserving the original data.In order to account for multiple values with minimal hassle,
Headersfollows this logic:- When getting a header with
headers[name]: if there’s no value,
KeyErroris raised;if there’s exactly one value, it’s returned;
if there’s more than one value,
MultipleValuesErroris raised.
- When getting a header with
When setting a header with
headers[name] = value, the value is appended to the list of values for that header.When deleting a header with
del headers[name], all values for that header are removed (this is slow).
Other methods for manipulating headers are consistent with this logic.
As long as no header occurs multiple times,
Headersbehaves likedict, except keys are lower-cased to provide case-insensitivity.get_all()returns a list of all values for a header andraw_items()returns an iterator of(name, values)pairs, similar tohttp.client.HTTPMessage().
- exception websockets.http.MultipleValuesError[source]¶
Exception raised when
Headershas more than one value for a key.
- websockets.http.read_request(stream)[source]¶
Read an HTTP/1.1 GET request from
stream.streamis anStreamReader.Return
(path, headers)wherepathis astrandheadersis aHeadersinstance.pathisn’t URL-decoded or validated in any way.Non-ASCII characters are represented with surrogate escapes.
Raise an exception if the request isn’t well formatted.
Don’t attempt to read the request body because WebSocket handshake requests don’t have one. If the request contains a body, it may be read from
streamafter this coroutine returns.
- websockets.http.read_response(stream)[source]¶
Read an HTTP/1.1 response from
stream.streamis anStreamReader.Return
(status_code, headers)wherestatus_codeis aintandheadersis aHeadersinstance.Non-ASCII characters are represented with surrogate escapes.
Raise an exception if the response isn’t well formatted.
Don’t attempt to read the response body, because WebSocket handshake responses don’t have one. If the response contains a body, it may be read from
streamafter this coroutine returns.