如何跨设备连接websocket服务器?

问题描述 投票:0回答:1

所以我试图让一个 websocket 与 websockets python 模块一起工作。 websockets 文档有一些简单的服务器和客户端示例,它们在同一设备上运行时运行良好,但当我尝试跨设备使用它时,它无法连接。我是 websockets 的新手,所以任何帮助将不胜感激。

这是来自 websockets 文档的回显服务器示例:

import asyncio
from websockets.server import serve

async def echo(websocket):
    async for message in websocket:
        await websocket.send(message)

async def main():
    async with serve(echo, "localhost", 8765):
        await asyncio.Future()  # run forever

asyncio.run(main())

这是客户示例:

import asyncio
from websockets.sync.client import connect

def hello():
    with connect("ws://localhost:8765") as websocket:
        websocket.send("Hello world!")
        message = websocket.recv()
        print(f"Received: {message}")

hello()

我查看了 websockets 文档。很多事情都让我头疼,但有一部分是在谈论将服务器部署到某个托管服务。我想知道是否可以只将我的计算机作为服务器运行,并让其他人在不使用这种服务的情况下通过互联网连接。

python websocket server client connect
1个回答
0
投票

没关系,我想通了。如果有人需要知道,服务器应该是:

import asyncio
from websockets.server import serve

async def echo(websocket):
    async for message in websocket:
        await websocket.send(message)
        print('recieved request')

async def main():
    async with serve(echo, "", 3324):
        await asyncio.Future()  # run forever

asyncio.run(main())

客户应该是:

import asyncio
from websockets.sync.client import connect

def hello():
    with connect("ws://xxx.xxx.x.xx:3324") as websocket:
    websocket.send("Hello world!")
    message = websocket.recv()
    print(f"Received: {message}")

hello()

其中 x 是主机的 IP 地址。

© www.soinside.com 2019 - 2024. All rights reserved.