A-A+

python websockets 与 websocket-client 使用示例

2024年05月07日 20:02 学习笔记 暂无评论 共3673字 (阅读77 views次)

【注意:此文章为博主原创文章!转载需注意,请带原文链接,至少也要是txt格式!】

使用 websocket-client 库来处理的修改后的代码:

 

import websocket
import threading
import time

#用于判断时间
last_message_time = 0

def on_message(ws, message):
    global last_message_time
    print("Received message:", message)
    last_message_time = time.time()  # 更新最后一次收到消息的时间

    if message == "1":
        print("abc")
    elif message == "2":
        print("bdc")
    elif message == "3":
        print("efg")


def on_error(ws, error):
    print("Error:", error)


def on_close(ws, *args):
    print("WebSocket closed")


def on_open(ws):
    print("WebSocket opened")
    threading.Thread(target=send_messages, args=(ws,), daemon=True).start()


def send_messages(ws):
    try:
        # 发送消息 "1"
        ws.send("1")    ##只要发送信息就会通过on_message接收到回包信息。
        print("Sent message: 1")
        time.sleep(2)


        # 发送消息 "2"
        ws.send("2")
        print("Sent message: 2")
        time.sleep(2)

        # 发送消息 "3"
        ws.send("3")
        print("Sent message: 3")

        while True:
            if time.time() - last_message_time > 30:  # 如果超过60秒未收到消息
                print("No message received for 30 seconds, closing connection")
                ws.close()
                break
            time.sleep(2)  # 每秒检查一次是否超时

    except Exception as e:
        print("Error while sending message:", e)


if __name__ == "__main__":
    websocket_url = "ws://110.118.214.131:7766/"

    ws = websocket.WebSocketApp(websocket_url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open

    ws.run_forever()

 

使用 websocket-client 库 进阶版本处理的修改后的代码:

&nbsp

import websocket
import threading
import time

#用于判断时间
last_message_time = 0

def on_message(ws, message):
    global last_message_time
    print("Received message:", message)
    last_message_time = time.time()  # 更新最后一次收到消息的时间

    if message == "1":
        print("abc")
    elif message == "2":
        print("bdc")
    elif message == "3":
        print("efg")


def on_error(ws, error):
    print("Error:", error)


def on_close(ws, *args):
    print("WebSocket closed")


def on_open(ws):
    print("WebSocket opened")
    threading.Thread(target=send_messages, args=(ws, "1"), daemon=True).start()
    threading.Thread(target=send_messages, args=(ws, "2"), daemon=False).start()
    threading.Thread(target=Check_if_online, args=(ws,), daemon=True).start()
    threading.Thread(target=send_messages, args=(ws, "3"), daemon=True).start()


def send_messages(ws, message):
    try:
        if message == "2":
            time.sleep(20)
            print("22222222")
        elif message == "3":
            time.sleep(25)
            print(3333333)
        ws.send(message)
        print("Sent message:", message)

    except Exception as e:
        print("Error while sending message:", e)

def Check_if_online(ws):
    try:
        global last_message_time
        time.sleep(10)
        while True:
            if time.time() - last_message_time > 15:  # 如果超过60秒未收到消息
                print("No message received for 30 seconds, closing connection")
                ws.close()
                break
            time.sleep(2)  # 每秒检查一次是否超时
    except Exception as e:
        print("Error while sending message:", e)


if __name__ == "__main__":
    websocket_url = "ws://110.118.214.131:7766/"

    ws = websocket.WebSocketApp(websocket_url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open

    ws.run_forever()

 

使用 websockets 库 进阶版本处理的修改后的代码:

&nbsp

import asyncio
import websockets


async def on_open(ws):
    print("WebSocket opened")
    await send_message_with_response(ws, "1")   ##例如是登录动作。
    await send_message_with_response2(ws)  ##例如是登录动作。


async def send_message_with_response(ws, message):
    try:
        await ws.send(message)
        print("Sent message:", message)
        try:
            response = await asyncio.wait_for(ws.recv(), timeout=10)
            print("Received response:", response)
        except asyncio.TimeoutError:
            print("No response from server")

        await asyncio.sleep(5)

    except websockets.ConnectionClosed:
        print("WebSocket connection closed")

async def send_message_with_response2(ws):
    try:
        while True:
            _text = input("please enter your context: ")
            if _text == "exit":
                print(f'you have enter "exit", goodbye')
                await ws.close(reason="user exit")
                return False
            await ws.send(_text)
            recv_text = await asyncio.wait_for(ws.recv(), timeout=10)
            print(f"{recv_text}")
    except websockets.ConnectionClosed:
        print("WebSocket connection closed")


async def main():
    uri = "ws://110.118.214.131:7766/"

    try:
        async with websockets.connect(uri) as ws:
            ##这里可以加入while True 来循环获取消息。
            await on_open(ws)   ##  其实这里就可以用ws.send(message) 进行消息发送,然后手动接收了。 用函数可以放入更多的动作

    except Exception as e:
        print("Connection error:", e)


asyncio.run(main())

布施恩德可便相知重

微信扫一扫打赏

支付宝扫一扫打赏

×

给我留言