How to implement websocket service in Python3?

PythonImplementing websocketthe service is very simple. There are many third-party packages available. I found three commonly used packages on the Internet: websocket, websockets, Flask-Sockets.

But many of these packages are in "disrepair", for example, they have not been maintained websocketin 2016.2010

Insert image description here

And Flask-Socketsalso 2016stopped maintenance in year.

Insert image description here

This also reminds us that when using a third-party package, be sure to check whether the package is still being maintained. If the author has stopped maintaining it, then be sure not to use it again, because it won’t take long for you to eat it. Big loss.

websockets

After excluding two packages that are no longer maintained, there is only one left websockets. So will this package meet our needs?

First of all websockets, I took a look and found that the community is still under maintenance recently, and websocketsit also has complete source code and usage tutorials, which is very friendly to novices.
Insert image description here
Insert image description here
Insert image description here

Source code and tutorial addresses:
https://pypi.org/project/websockets/
https://github.com/python-websockets/websockets
https://websockets.readthedocs.io/en/stable/intro/tutorial1.html

Example:

service.py

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import asyncio
import websockets


async def hello(websocket):
    recv_data = await websocket.recv()
    print('<<< %s' % recv_data)

    send_data = 'Hello %s' % recv_data
    await websocket.send(send_data)
    print('>>> %s' % send_data)


async def start():
    print('Server started ...')
    async with websockets.serve(hello, '0.0.0.0', 8765):
        await asyncio.Future()


if __name__ == '__main__':
    asyncio.run(start())

client.py

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import asyncio
import websockets


async def hello():
    uri = 'ws://0.0.0.0:8765'
    async with websockets.connect(uri) as websocket:

        send_data = input("What's your name: ")

        await websocket.send(send_data)
        print('>>> %s' % send_data)

        recv_data = await websocket.recv()
        print('<<< %s' % recv_data)


if __name__ == '__main__':
    asyncio.run(hello())

This is a simple WebSocketserver/client program, and it is also WebSocketthe core thing in it.

operation result:

Insert image description here

Insert image description here

But there is a problem with this. The server closes the connection after receiving a message. If you want to achieve a persistent connection, you need to use a loop to handle it.

async with websockets.connect(uri) as websocket:
    for i in range(10):
        send_data = input("What's your name: ")
        ...

If asynchronous is used, you need to add async:

async def handler(websocket):
    async for message in websocket:
        print(message)

Sometimes there may be a problem that only one client can connect at a time. Generally speaking, this is caused by not using asynchronous time calls in the program.

For example, this connection handler prevents the event loop from running for one second:

async def handler(websocket):
    time.sleep(1)
    ...

Change it to:

async def handler(websocket):
    await asyncio.sleep(1)
    ...

How to start multiple processes?

If you want to start multiple processes, you can use Pythonthe built-in package to implement it. First import the process pool module, and then start all processes. For multi-process usage, please refer to the article Python3 Multi-process Programming .

from multiprocessing import Pool

...

def main():
    asyncio.run(start())

if __name__ == '__main__':
    p = Pool(30)
    for i in range(10):
        p.apply_async(main)

    p.close()
    p.join()
    ...

For more tips and FAQs, please refer to: https://websockets.readthedocs.io/en/stable/faq/server.html

Guess you like

Origin blog.csdn.net/yilovexing/article/details/133124547