python - Howto Python Push websocket 客户端,教程?尝试 pusher 没有成功(不完整的例子?)
问题描述
我是 websocket 和推送技术的新手。我必须开发一个基于 Python(在 RPI 上)的推送客户端来与服务器通信。
推送服务器基于 Push Laravel 技术,(push + websocket)。通过 https + 登录名/密码注册保护对服务器的访问。
我可以使用 htpps 连接/注册到服务器,但我不知道如何订阅服务器的频道。
我在这里找到了一个 python 推送客户端的示例https://github.com/deepbrook/Pysher以及这里的问题:Receiving events in Pusher client 但我认为这些示例并不完整,因为在这些示例中未指定 WS 服务器编码...
这是我所做的(我删除了机密信息并替换为...):
global pusher
LOGIN_URL = ...
URL = ...
EMAIL= ...
PASSWORD= ...
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
client = requests.session()
response=client.get(LOGIN_URL)
soup = BeautifulSoup(response.text, 'html.parser')
csrftoken = soup.select_one('meta[name="csrftoken"]')['content']
login_data = dict(_token=csrftoken,email=EMAIL, password=PASSWORD, )
r = client.post(URL, data=login_data, headers=dict(Referer=URL))
ws = create_connection("wss://......../app/...key...?protocol=7&client=js&version=7.0.0&flash=false")
root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
root.addHandler(ch)
def my_func(*args, **kwargs):
print("processing Args:", args)
print("processing Kwargs:", kwargs)
def connect_handler(data):
channel = pusher.subscribe('presence-chat')
channel.bind('App\\Events\\MessageSent', my_func)
appkey='....'
PUSHER_APP_ID='..'
PUSHER_APP_KEY='...'
PUSHER_APP_SECRET='...'
PUSHER_APP_CLUSTER='...'
pusher = pusherclient.Pusher(PUSHER_APP_ID, PUSHER_APP_KEY, PUSHER_APP_SECRET, PUSHER_APP_CLUSTER)
pusher.connection.bind('pusher:connection_established', connect_handler)
pusher.connect()
while True:
# Do other things in the meantime here...
time.sleep(1)
但是执行时出现这些错误:
error from callback <bound method Connection._on_open of <Connection(Thread-1, started daemon 14552)>>: _on_open() missing 1 required positional argument: 'ws'
error from callback <bound method Connection._on_message of <Connection(Thread-1, started daemon 14552)>>: _on_message() missing 1 required positional argument: 'message'
error from callback <bound method Connection._on_close of <Connection(Thread-1, started daemon 14552)>>: _on_close() missing 1 required positional argument: 'ws'
可能是因为我没有指定推送器的 WS 服务器地址,但我不知道该怎么做(令人惊讶的是,我在上面找到的示例也没有指定这样的 WS 地址)。
另一种可能性是仅使用 python websocket lib(所以没有 pusher lib)直接编写推送对话框,如下所示:
client = requests.session()
response=client.get(LOGIN_URL)
soup = BeautifulSoup(response.text, 'html.parser')
csrftoken = soup.select_one('meta[name="csrf-token"]')['content']
login_data = dict(_token=csrftoken,email=EMAIL, password=PASSWORD, )
r = client.post(URL, data=login_data, headers=dict(Referer=URL))
async def hello():
async with websockets.connect(
URI, ssl=True #ssl_context
) as websocket:
name = input("Message to send ? ")
await websocket.send(name)
print(f"Sent message : {name}")
greeting = await websocket.recv()
print(f"Received : {greeting}")
asyncio.get_event_loop().run_until_complete(hello())
使用此代码,我可以建立连接:
"event":"pusher:connection_established","data":"{\"socket_id\":\"54346.8202313328\",\"activity_timeout\":30}"}
但我不知道如何订阅频道。我想我必须使用 json 等形成一个命令,但需要一些例子......
任何帮助,指针或任何东西都会非常感激,因为我现在完全迷路了。
2021 年万事如意,不能像今年一样糟糕!问候, 大气
解决方案
最后我解决了问题:推送服务器地址被硬编码在类推送器文件“pusherclient/ init .py”中,host="wss:ws....com"
不幸的是,我仍然有一些错误:
error from callback <bound method Connection._on_error of <Connection(Thread-1, started daemon 8332)>>: _on_error() missing 1 required positional argument: 'error'
error from callback <bound method Connection._on_close of <Connection(Thread-1, started daemon 8332)>>: _on_close() missing 1 required positional argument: 'ws'
推荐阅读
- java - 使用来自不同数据源的大量数据的架构设计
- entity-framework-core - 属性“Entity1.Entity2”的类型为“Entity2”,当前数据库提供程序不支持
- java - 如何根据数组列表中每个对象的属性将自定义对象的数组列表分成 x 组?
- python-3.x - 在具有负奖励的图中找到最短路径时,策略梯度 (REINFORCE) 发散
- python - 在 python 中使用 GPU 加速蒙特卡罗模拟
- javascript - 使用 deleteOne 方法发布请求以从 mongodb 数据库中删除项目
- python - python - 如何在遇到python条件时停止函数运行?
- c++ - 如何解决“无法打开'raise.c'”错误?(VSCODE,LINUX)
- debugging - Rust LLVM 链接器 (rust-lld) 段错误
- tensorflow - 使用 tf.keras 模型训练时 GPU 随机冻结