最简服务器&客户端!Python3 Websockets 嵌入式开发初体验

前言

    本文主要介绍了通过Python3 的 Websockets模块来建立最简单的服务器/客户端连接通信的方法。此方法适用于嵌入式开发者对Python3 Websockets模块快速上手,了解相关原理后,即可让两设备进行数据通信。

    至于如何安装Websockets模块,在上一篇文章我有说到。点击--> 在Ubuntu中安装Python3 websockets模块

    本文参考资料:http://websockets.readthedocs.io/en/stable/intro.html

运行环境

    Ubuntu 18.04

    Vmware 12 Pro

    Python 3.6.5(不能低于 Python 3.4)

服务器 Server

    代码:

#!/usr/bin/python3

import websockets
import asyncio

async def hello(websocket,path):
		name = await websocket.recv()
		print(f"A new client : {name}")
		greeting = "Welcome " + name
		await websocket.send(greeting)
		print(f"send '{greeting}' to '{name}'")
		
start_server = websockets.serve(hello,'localhost',8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

客户端 Client

    代码:

#!/usr/bin/python3

import websockets
import asyncio

async def hello():
	async with websockets.connect('ws://localhost:8765') as websocket:
		name = input("what's your name?")
		await websocket.send(name)
		print(f"send server:{name}")
		greeting = await websocket.recv()
		print(f"receive from server:{greeting}")
asyncio.get_event_loop().run_until_complete(hello())

实际运行情况

    首先,运行服务器执行文件 test_websocket_server.py;

    然后,在另一终端运行客户端文件 test_websocket_client.py,并键盘输入名字 Chile 并按回车(可随意输入);

    接着,服务器会收到客户端输入的名字 Chile,客户端也会收到服务器回复的信息;

    最后,客户端会关闭websocket连接,服务器会继续等待下一客户端进行连接。

    

猜你喜欢

转载自blog.csdn.net/chile19/article/details/80581674