python之websocket

简易的客户端和服务端通信,不包含验证和加密

pip install websockets

pip install websocket

pip install websocket-client

  • 客户端
# websocket协议通信
import threading
import time
import websocket

def when_message(ws, message):
    print('接收到的消息:' + message)


# 当建立连接后,死循环不断输入消息发送给服务器
# 这里需要另起一个线程
def when_open(ws):
    def run():
        while True:
            a = input('发送服务端:')
            ws.send(a)
            time.sleep(0.5)
            if a == 'close':
                ws.close()
                break

    t = threading.Thread(target=run)
    # t.setDaemon(True)
    t.start()

def when_close(ws):
    print('连接关闭')

if __name__ == '__main__':
    ws = websocket.WebSocketApp('ws://localhost:8765/', on_message=when_message, on_open=when_open, on_close=when_close)
    ws.run_forever()
  • 服务端
import asyncio
import websockets


async def echo(websocket, path):
    async for message in websocket:
        print(message)
        # 发送客户端
        # message = "返回到客户端: {}".format(message)
        # await websocket.send(message)


asyncio.get_event_loop().run_until_complete(websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()

你可能感兴趣的:(Python,python,websocket,开发语言,1024程序员节)