searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

python3 异步域通信样例

2024-11-15 09:17:58
0
0

server

import asyncio
import os

# 定义 Unix 域套接字路径
SOCKET_PATH = '/tmp/unix_socket'

async def handle_client(reader, writer):
    data = await reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')
    print(f"Received {message!r} from {addr!r}")

    print("Send: Hello, Client!")
    writer.write(b'Hello, Client!')
    await writer.drain()

    print("Close the connection")
    writer.close()
    await writer.wait_closed()

async def main():
    # 如果套接字文件已存在,先删除
    if os.path.exists(SOCKET_PATH):
        os.remove(SOCKET_PATH)

    server = await asyncio.start_unix_server(handle_client, SOCKET_PATH)
    async with server:
        await server.serve_forever()

if __name__ == '__main__':
    asyncio.run(main())

client

import asyncio
import os

# 定义 Unix 域套接字路径
SOCKET_PATH = '/tmp/unix_socket'

async def main():
    reader, writer = await asyncio.open_unix_connection(SOCKET_PATH)

    print("Send: Hello, Server!")
    writer.write(b'Hello, Server!')
    await writer.drain()

    data = await reader.read(100)
    message = data.decode()
    print(f"Received: {message!r}")

    print("Close the connection")
    writer.close()
    await writer.wait_closed()

if __name__ == '__main__':
    asyncio.run(main())
0条评论
0 / 1000
s****n
8文章数
0粉丝数
s****n
8 文章 | 0 粉丝
原创

python3 异步域通信样例

2024-11-15 09:17:58
0
0

server

import asyncio
import os

# 定义 Unix 域套接字路径
SOCKET_PATH = '/tmp/unix_socket'

async def handle_client(reader, writer):
    data = await reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')
    print(f"Received {message!r} from {addr!r}")

    print("Send: Hello, Client!")
    writer.write(b'Hello, Client!')
    await writer.drain()

    print("Close the connection")
    writer.close()
    await writer.wait_closed()

async def main():
    # 如果套接字文件已存在,先删除
    if os.path.exists(SOCKET_PATH):
        os.remove(SOCKET_PATH)

    server = await asyncio.start_unix_server(handle_client, SOCKET_PATH)
    async with server:
        await server.serve_forever()

if __name__ == '__main__':
    asyncio.run(main())

client

import asyncio
import os

# 定义 Unix 域套接字路径
SOCKET_PATH = '/tmp/unix_socket'

async def main():
    reader, writer = await asyncio.open_unix_connection(SOCKET_PATH)

    print("Send: Hello, Server!")
    writer.write(b'Hello, Server!')
    await writer.drain()

    data = await reader.read(100)
    message = data.decode()
    print(f"Received: {message!r}")

    print("Close the connection")
    writer.close()
    await writer.wait_closed()

if __name__ == '__main__':
    asyncio.run(main())
文章来自个人专栏
python样例
1 文章 | 1 订阅
0条评论
0 / 1000
请输入你的评论
0
0