websocket技术简单来说就是实现了长连接的技术,相对于传统的ajax或者轮询,websocket主要实现了双通信,并且减少了长轮询的多次请求的时间。总的来说,在很多应用上面能够发挥更好的作用,比如在线聊天等。下面主要写下python下面的server端的实现代码,以及client端代码,最终是浏览器端的js实现的client代码。
python的server端:
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)
print(message)
asyncio.get_event_loop().run_until_complete(
websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()
python的client端:
import asyncio
import websockets
import time
async def hello(uri):
async with websockets.connect(uri) as websocket:
while True:
send=input("输入要发送的内容:")
await websocket.send(send)
greeting = await websocket.recv()