我用 python 写了一个 websockets 例子, 服务端和客户端在一台服务器上就可以正常通信,
放在不同的服务器就会提示
error:websockets.exceptions.InvalidMessage: did not receive a valid HTTP response 。
是不是网络的问题,不过我服务器防火墙上的端口都打开了。
sever.py 服务端
import asyncio
import websockets
# 检测客户端权限,用户名密码通过才能退出循环
async def check_permit(websocket):
while True:
recv_str = await websocket.recv()
cred_dict = recv_str.split(":")
print("接受",cred_dict)
if cred_dict[0] == "admin" and cred_dict[1] == "123456":
response_str = "congratulation, you have connect with server\r\nnow, you can do something else"
await websocket.send(response_str)
return True
else:
response_str = "sorry, the username or password is wrong, please submit again"
await websocket.send(response_str)
# 接收客户端消息并处理,这里只是简单把客户端发来的返回回去
async def recv_msg(websocket):
while True:
recv_text = await websocket.recv()
print("消息:",str(recv_text))
response_text = f"your submit context: {recv_text}"
await websocket.send(response_text)
# 服务器端主逻辑
# websocket 和 path 是该函数被回调时自动传过来的,不需要自己传
async def main_logic(websocket, path):
await check_permit(websocket)
await recv_msg(websocket)
start_server = websockets.serve(main_logic, '0.0.0.0', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
#### client.py 客户端
import asyncio
import websockets
# 向服务器端认证,用户名密码通过才能退出循环
async def auth_system(websocket):
while True:
cred_text = input("please enter your username and password: ")
await websocket.send(cred_text)
response_str = await websocket.recv()
if "congratulation" in response_str:
return True
# 向服务器端发送认证后的消息
async def send_msg(websocket):
while True:
_text = input("please enter your context: ")
if _text == "exit":
print(f'you have enter "exit", goodbye')
await websocket.close(reason="user exit")
return False
await websocket.send(_text)
recv_text = await websocket.recv()
print(f"{recv_text}")
# 客户端主逻辑
async def main_logic():
async with websockets.connect('ws://(server 公网 ip):8765') as websocket:
await auth_system(websocket)
await send_msg(websocket)
asyncio.get_event_loop().run_until_complete(main_logic())
1
julyclyde 2023-01-16 08:32:17 +08:00
在 client 里设置一下 logging 吧
import logging logging.basicConfig(level=logging.DEBUG) |
2
thinkershare 2023-01-16 20:01:35 +08:00
你这样提问,别人很难告诉你原因,我扫了一下,代码没问题。这个错误就是客户端连接不到服务器。应该是中间的网络环境问题,你先 ping 一下公网 IP ,然后在你的服务器上查看一下当前服务 8765 监听的 IP 地址列表,最后确认一下这个流程的中间是否存在代理和防火墙规则。
|