温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python Linux下实现Websocket通信

发布时间:2024-09-11 23:38:40 来源:亿速云 阅读:78 作者:小樊 栏目:编程语言

在Linux下使用Python实现WebSocket通信,你可以使用websockets

pip install websockets

接下来,我们将创建一个简单的WebSocket服务器和客户端。

WebSocket服务器

创建一个名为websocket_server.py的文件,然后添加以下代码:

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        print(f"Received message: {message}")
        await websocket.send(f"Echo: {message}")

start_server = websockets.serve(echo, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

这个脚本创建了一个WebSocket服务器,它将侦听localhost上的8765端口。当收到客户端发送的消息时,服务器会将消息打印到控制台,并将相同的消息回显给客户端。

WebSocket客户端

创建一个名为websocket_client.py的文件,然后添加以下代码:

import asyncio
import websockets

async def hello():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello, world!")
        response = await websocket.recv()
        print(f"Received response: {response}")

asyncio.get_event_loop().run_until_complete(hello())

这个脚本创建了一个WebSocket客户端,它将连接到localhost上的8765端口。然后,客户端向服务器发送一条消息,并等待服务器的回应。当收到服务器的回应时,客户端将打印回应到控制台。

运行示例

首先,运行WebSocket服务器:

python websocket_server.py

然后,在另一个终端中运行WebSocket客户端:

python websocket_client.py

你应该会在两个终端中看到相应的输出。服务器将显示收到的消息,而客户端将显示从服务器接收到的回应。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI