用Python实现的WebSocket服务器
发布时间:2023-12-27 13:07:17
WebSocket是一种全双工通信协议,允许服务端与客户端之间进行实时的双向数据传输。在Python中,我们可以使用第三方库websockets来实现WebSocket服务器。
首先,我们需要安装websockets库,在命令行中运行以下命令:
pip install websockets
接下来,我们可以使用以下代码实现一个简单的WebSocket服务器:
import asyncio
import websockets
# 在连接建立时调用的函数
async def handle_connection(websocket, path):
# 发送初始消息给客户端
await websocket.send("连接成功!")
try:
while True:
# 接收客户端发送的消息
message = await websocket.recv()
print(f"收到消息:{message}")
# 发送消息给客户端
await websocket.send(f"收到消息:{message}")
except websockets.exceptions.ConnectionClosedOK:
print("连接已关闭!")
# 启动WebSocket服务器
start_server = websockets.serve(handle_connection, "localhost", 8000)
# 运行事件循环
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
在上面的代码中,我们定义了一个handle_connection函数,它会在每个连接建立时被调用。在该函数中,我们首先使用websocket.send发送初始消息给客户端,然后进入一个无限循环,使用websocket.recv接收客户端发送的消息,并使用websocket.send将收到的消息发送回客户端。
最后,我们使用websockets.serve函数创建一个WebSocket服务器,并指定监听的主机和端口。然后,我们使用asyncio.get_event_loop().run_until_complete启动服务器,并使用asyncio.get_event_loop().run_forever运行事件循环。
我们可以使用以下代码连接到WebSocket服务器并发送消息:
import asyncio
import websockets
async def send_message():
async with websockets.connect("ws://localhost:8000/") as websocket:
while True:
message = input("请输入消息:")
await websocket.send(message)
response = await websocket.recv()
print(f"收到响应:{response}")
# 运行事件循环
asyncio.get_event_loop().run_until_complete(send_message())
在上面的代码中,我们使用websockets.connect函数连接到WebSocket服务器,并使用websocket.send发送消息。然后,我们使用websocket.recv接收服务器的响应,并打印出来。
将上面的两段代码分别保存为两个Python文件,分别运行它们,即可实现一个简单的WebSocket服务器和客户端的通信。
这样就是使用Python实现WebSocket服务器的简单例子了。希望对你有所帮助!
