Python asyncore模块-客户端

本文介绍了如何使用asyncore模块简化Python的异步socket服务器开发,包括事件循环、dispatcher基础架构、客户端socket编程和回调函数的实现。同时,给出了使用示例和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍

这个模块为异步socket的服务器通信提供简单的接口。该模块提供了异步socket服务端和服务器的基础架构。相比python原生的socket API,asyncore具有很大的优势,asyncore对原生的socket进行了封装,提供非常简洁优秀的接口,利用asyncore重写相关需要处理的接口,就可以完成一个socket的网络编程,从而不需要处理复杂的socket网络状况及多线程处理等等。

使用asyncore框架时,需要注意两点:

1) 全局函数loop

  • 创建asyncore的事件循环
  • 在事件循环中调用底层的select方法来检测特定的网络信道,如果信道对应的socket对象状态发生改变,则自动产生一个高层次的事件信息,然后针对该信息调用的回调方法进行处理。

2) 基类dispatcher

  • dispatcher类是一个底层socket类的封装对象,必须在编程中继承于dispatcher类或其子类,dispatcher类里面已经定义好了通信中的各种事件,只需要重写特定的事件即可在该事件发生时实现自动回调处理。

客户端socket开发基本使用

1)导入:import asyncore
2)定义类并继承自asyncore.dispatcherclass SocketClient(asyncore.dispatcher)
3).实现类中的回调代码def  __init__(self,host,port)

  • 调用父类方法asyncore.dispatcher.__init__(self)
  • 创建socket对象self.create_socket()
  • 链接服务器address=(host,port)
  • self.connect(address)

4)创建对象并执行asyncore.loop 

  • SocketClient('127.0.0.1',9999)
  • 开始启动运行循环asyncore.loop(timeout=5)

5) 其它回调函数:

  • handle_connect回调函数:实现连接回调。当Socket连接服务器成功时回调函数
def handle_connect(self):
    print("连接成功")
  • writable:描述是否数据需要被发送到服务器。返回值为True,表示可写,False表示不可写,如果不实现默认返回为True,当返回True时,回调函数handle_writee被触发。
def writable(self):
    return True
  • handle_write:当有数据需要发送时(writable回调函数返回True),该函数被触发,通常情况在该函数中编写send方法发送数据。
# 实现handle_write回调函数
def  handle_write(self):
    #内部实现对服务器发送数据的代码
    #调用send方法发送数据,参数是字节数据
    self.send("hello ".encode('utf-8'))
  • readable回调函数:描述是否有数据从服务器读取。返回True表示数据需要读取,False表示没有数据需要被读取,当不实现默认返回为True时,当返回True时,回调函数handle_read被触发。
def readable(self):
    return True
  • handle_read:主动接收数据,参数是需要接收数据的长度
def handle_read(self):
    result = self.recv(1024)
    print(result)
  • handle_error:当程序运行发生异常时回调该函数
def handle_error(self):
    # 编写处理错误的方法
    t, e, trace = sys.exc_info()
    print(e)
  • handle_close:当连接关闭时被触发。
def handle_close(self):
    # 主动调用关闭函数
    print("连接关闭")
    self.close()

测试示例

使用linux中nc命令监听9999端口:

[blctrl@main-machine ~]$ nc -l 9999

asyncore的客户端代码useasyncore,它每2秒种向服务器发送一个hello字符串,并且显示其从服务器接收到的字符串:

#!/usr/bin/env python3

import asyncore,sys
import time

class SocketClient(asyncore.dispatcher):
    def __init__(self, ip, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.addr = (ip ,port)
        self.connect(self.addr)

    def handle_connect(self):
        print("connect to server %s %d successfully" % self.addr)

    def writable(self):
        return True

    def handle_write(self):
        time.sleep(2)
        self.send('hello\n'.encode())

    def readable(self):
        return True

    def handle_read(self):
        print(self.recv(1024))

    def handle_error(self):
        t,e,trace = sys.exc_info()
        print(e)
        self.close()

    def handle_close(self):
        print("close the connection")
        self.close()

if __name__ == '__main__':
    SocketClient('192.168.50.181', 9999)
    asyncore.loop()

运行以上python代码代码:

orangepi@orangepi5:~/python_program$ ./useasyncore.py
/home/orangepi/python_program/./useasyncore.py:3: DeprecationWarning: The asyncore module is deprecated and will be removed in Python 3.12. The recommended replacement is asyncio
  import asyncore,sys
connect to server 192.168.50.181 9999 successfully

服务器端,每2秒钟,接收一个字符串hello:

[blctrl@main-machine ~]$ nc -l 9999
hello
hello
...

在服务器端,输入一个world字符串,按回车,观察客户端中接收到了一个字节流world\n:

orangepi@orangepi5:~/python_program$ ./useasyncore.py
/home/orangepi/python_program/./useasyncore.py:3: DeprecationWarning: The asyncore module is deprecated and will be removed in Python 3.12. The recommended replacement is asyncio
  import asyncore,sys
connect to server 192.168.50.181 9999 successfully
b'world\n'
...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值