(1)TypeError: echo() missing 1 required positional argument: 'path'報錯
自己寫的代碼如下:
async def echo(websocket, path):...
async def main():server = await websockets.serve(echo, "0.0.0.0", 666)await server.wait_closed()
在echo中有兩個變量websocket和path卻在運行時候報錯TypeError: echo() missing 1 required positional argument: 'path',查閱資料據說時因為版本的問題,查看源代碼也只有一個參數
源碼解釋如下:
class serve:"""Create a WebSocket server listening on ``host`` and ``port``.Whenever a client connects, the server creates a :class:`ServerConnection`,performs the opening handshake, and delegates to the ``handler`` coroutine.The handler receives the :class:`ServerConnection` instance, which you canuse to send and receive messages.Once the handler completes, either normally or with an exception, the serverperforms the closing handshake and closes the connection.This coroutine returns a :class:`Server` whose API mirrors:class:`asyncio.Server`. Treat it as an asynchronous context manager toensure that the server will be closed::from websockets.asyncio.server import servedef handler(websocket):...# set this future to exit the serverstop = asyncio.get_running_loop().create_future()async with serve(handler, host, port):await stopAlternatively, call :meth:`~Server.serve_forever` to serve requests andcancel it to stop the server::server = await serve(handler, host, port)await server.serve_forever()Args:handler: Connection handler. It receives the WebSocket connection,which is a :class:`ServerConnection`, in argument.host: Network interfaces the server binds to.See :meth:`~asyncio.loop.create_server` for details.port: TCP port the server listens on.See :meth:`~asyncio.loop.create_server` for details.origins: Acceptable values of the ``Origin`` header, for defendingagainst Cross-Site WebSocket Hijacking attacks. Values can be:class:`str` to test for an exact match or regular expressionscompiled by :func:`re.compile` to test against a pattern. Include:obj:`None` in the list if the lack of an origin is acceptable.extensions: List of supported extensions, in order in which theyshould be negotiated and run.subprotocols: List of supported subprotocols, in order of decreasingpreference.select_subprotocol: Callback for selecting a subprotocol amongthose supported by the client and the server. It receives a:class:`ServerConnection` (not a:class:`~websockets.server.ServerProtocol`!) instance and a list ofsubprotocols offered by the client. Other than the first argument,it has the same behavior as the:meth:`ServerProtocol.select_subprotocol<websockets.server.ServerProtocol.select_subprotocol>` method.compression: The "permessage-deflate" extension is enabled by default.Set ``compression`` to :obj:`None` to disable it. See the:doc:`compression guide <../../topics/compression>` for details.process_request: Intercept the request during the opening handshake.Return an HTTP response to force the response or :obj:`None` tocontinue normally. When you force an HTTP 101 Continue response, thehandshake is successful. Else, the connection is aborted.``process_request`` may be a function or a coroutine.process_response: Intercept the response during the opening handshake.Return an HTTP response to force the response or :obj:`None` tocontinue normally. When you force an HTTP 101 Continue response, thehandshake is successful. Else, the connection is aborted.``process_response`` may be a function or a coroutine.server_header: Value of the ``Server`` response header.It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to:obj:`None` removes the header.open_timeout: Timeout for opening connections in seconds.:obj:`None` disables the timeout.ping_interval: Interval between keepalive pings in seconds.:obj:`None` disables keepalive.ping_timeout: Timeout for keepalive pings in seconds.:obj:`None` disables timeouts.close_timeout: Timeout for closing connections in seconds.:obj:`None` disables the timeout.max_size: Maximum size of incoming messages in bytes.:obj:`None` disables the limit.max_queue: High-water mark of the buffer where frames are received.It defaults to 16 frames. The low-water mark defaults to ``max_queue// 4``. You may pass a ``(high, low)`` tuple to set the high-waterand low-water marks. If you want to disable flow control entirely,you may set it to ``None``, although that's a bad idea.write_limit: High-water mark of write buffer in bytes. It is passed to:meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaultsto 32?KiB. You may pass a ``(high, low)`` tuple to set thehigh-water and low-water marks.logger: Logger for this server.It defaults to ``logging.getLogger("websockets.server")``. See the:doc:`logging guide <../../topics/logging>` for details.create_connection: Factory for the :class:`ServerConnection` managingthe connection. Set it to a wrapper or a subclass to customizeconnection handling.Any other keyword arguments are passed to the event loop's:meth:`~asyncio.loop.create_server` method.For example:* You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS.* You can set ``sock`` to provide a preexisting TCP socket. You may call:func:`socket.create_server` (not to be confused with the event loop's:meth:`~asyncio.loop.create_server` method) to create a suitable serversocket and customize it.* You can set ``start_serving`` to ``False`` to start accepting connectionsonly after you call :meth:`~Server.start_serving()` or:meth:`~Server.serve_forever()`."""
可以看到這里例子中也是只用了一個參數
from websockets.asyncio.server import servedef handler(websocket):...# set this future to exit the serverstop = asyncio.get_running_loop().create_future()async with serve(handler, host, port):await stop
改成一個參數后果然不報錯了,并且可以正常運行
(2)websockets.exceptions.ConnectionClosedError: sent 1011 (internal error) keepalive ping timeout; no close frame received
客戶端因為心跳超時而被服務器關閉,在自己寫的代碼中,由于使用input發送數據導致代碼阻塞而沒能及時響應服務器的心跳,因此被服務器斷開連接,這里要使用input的話可以使用asyncio庫中將輸出放在一個單獨的進程中運行,避免阻塞程序
原來代碼,有可能阻塞程序導致心跳超時
send_data = input("input data")
修改后代碼:
send_data = await asyncio.to_thread(input, "input data:")