如何模拟websocket客户端(websocket客户端和服务端)
如何模拟websocket客户端(websocket客户端和服务端)from websocket import create_connection # 客户端 def test(ws msg): ws = create_connection(ws) print("发送数据:%s"%msg) ws.send(msg) result = ws.recv() print("收到服务端返回的数据:%s" % result) ws.close() if __name__ == "__main__": ws = "ws://192.168.81.246:5678" msg = "nihao" test(ws msg) 执行:测试结果:
说明:
客户端发送数据给服务端,服务端接收后给客户端回一个消息:sucess,使用场景:有些项目使用的是websocket协议开发的产品,需对接口进行测试,并搭建自动化测试框架,更好的理解其原理
代码(服务端):
import asyncio
import websockets
# 服务端
async def echo(websocket path):
async for message in websocket:
print ('服务端接收到消息:%s'%message)
msg = "sucess"
await websocket.send(msg)
if __name__ == "__main__":
host = "192.168.81.246" #本机电脑ip地址
port = 5678
print ("启动服务")
asyncio.get_event_loop().run_until_complete(websockets.serve(echo host port))
asyncio.get_event_loop().run_forever()
代码(客户端):
from websocket import create_connection
# 客户端
def test(ws msg):
ws = create_connection(ws)
print("发送数据:%s"%msg)
ws.send(msg)
result = ws.recv()
print("收到服务端返回的数据:%s" % result)
ws.close()
if __name__ == "__main__":
ws = "ws://192.168.81.246:5678"
msg = "nihao"
test(ws msg)
执行:
测试结果: