python --连接websocket

如果只是模拟js端发送接收的话,已经有了websocket server的话,只有client就好了

pip install websocket-client
#-*- encoding:utf-8 -*-
  
import sys
sys.path.append("..")
from socket import *
import json, time, threading
from websocket import create_connection
  
  
class Client():
    def __init__(self):
        #调用create_connection方法,建立一个websocket链接,链接是自己的链接
        self.ws = create_connection("ws://127.0.0.1:10010/xxxx")
        #建一个线程,监听服务器发送给客户端的数据
        self.trecv = threading.Thread(target=self.recv)
        self.trecv.start()
 
  
    #发送方法,聊天输入语句时调用,此处默认为群聊ALL
    def send(self,content):
        #这里的msg要根据实际需要自己写
        msg={
    
    
            "type":"POST",
            "content":content
        }
        msg = json.dumps(msg)
        self.ws.send(msg)
  
    #接收服务端发送给客户的数据,只要ws处于连接状态,则一直接收数据
    def recv(self):
        try:
            while self.ws.connected:
                result = self.ws.recv()
                print "received msg:"+str(result)
        except Exception,e:
            pass 
  
if __name__ == '__main__':
  
    c= Client()
    #建立链接后,就可以按照需要自己send了
    c.send(content)

接下来,你可以使用以下代码来连接WebSocket服务器:

import websocket

def on_message(ws, message):
    print("Received message:", message)

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

def on_close(ws):
    print("WebSocket closed")

def on_open(ws):
    print("WebSocket connected")

# 连接的WebSocket服务器地址
websocket_url = "ws://example.com/websocket"

# 创建WebSocket连接
websocket.enableTrace(True) # 可选,用于调试。打开调试信息输出
ws = websocket.WebSocketApp(websocket_url,
                            on_message=on_message,
                            on_error=on_error,
                            on_close=on_close)
ws.on_open = on_open

# 开始WebSocket连接
ws.run_forever()

在上面的代码中,我们定义了四个回调函数on_messageon_erroron_closeon_open,分别用于处理接收到的消息、连接错
误、关闭连接和连接成功事件。你可以根据自己的需求来修改这些回调函数的具体行为。

注意,websocket_url变量应该是你要连接的WebSocket服务器的地址。如果需要,你还可以通过添加一些其他的参数来自定义WebSocket连接的行为,比如设置超时时间、HTTP代理等。

最后,调用ws.run_forever()方法来开始WebSocket连接。这个方法将会阻塞并保持连接,直到连接关闭或出现错误。

希望这个简单的示例能帮助你成功连接WebSocket服务器,并实现你想要的功能!

猜你喜欢

转载自blog.csdn.net/weixin_44634704/article/details/132237003