• Python asyncore模块-客户端


    介绍

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

    测试示例

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

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

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

    1. #!/usr/bin/env python3
    2. import asyncore,sys
    3. import time
    4. class SocketClient(asyncore.dispatcher):
    5. def __init__(self, ip, port):
    6. asyncore.dispatcher.__init__(self)
    7. self.create_socket()
    8. self.addr = (ip ,port)
    9. self.connect(self.addr)
    10. def handle_connect(self):
    11. print("connect to server %s %d successfully" % self.addr)
    12. def writable(self):
    13. return True
    14. def handle_write(self):
    15. time.sleep(2)
    16. self.send('hello\n'.encode())
    17. def readable(self):
    18. return True
    19. def handle_read(self):
    20. print(self.recv(1024))
    21. def handle_error(self):
    22. t,e,trace = sys.exc_info()
    23. print(e)
    24. self.close()
    25. def handle_close(self):
    26. print("close the connection")
    27. self.close()
    28. if __name__ == '__main__':
    29. SocketClient('192.168.50.181', 9999)
    30. asyncore.loop()

    运行以上python代码代码:

    1. orangepi@orangepi5:~/python_program$ ./useasyncore.py
    2. /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
    3. import asyncore,sys
    4. connect to server 192.168.50.181 9999 successfully

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

    1. [blctrl@main-machine ~]$ nc -l 9999
    2. hello
    3. hello
    4. ...

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

    1. orangepi@orangepi5:~/python_program$ ./useasyncore.py
    2. /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
    3. import asyncore,sys
    4. connect to server 192.168.50.181 9999 successfully
    5. b'world\n'
    6. ...
  • 相关阅读:
    字符函数、字符串函数和内存函数
    计算机毕业设计之java+ssm的摄影约拍系统的设计
    容器云资源数据关联与数据联动的难点和解决思路
    蓝牙核心规范(V5.4)12.1-深入详解之PAwR
    Springboot---整合对象储存服务MinIO
    【见刊通知】ISEEIE 2022 & COMSE 2022已见刊,请自行查看见刊链接 ~
    前端笔面编程收录【按公司】
    一文详解接口测试(调试)工具postman的安装(完全卸载)和使用以及接口管理
    模拟实现ATM系统——Java
    设计模式 - 解释器模式
  • 原文地址:https://blog.csdn.net/yuyuyuliang00/article/details/132846281