这个模块为异步socket的服务器通信提供简单的接口。该模块提供了异步socket服务端和服务器的基础架构。相比python原生的socket API,asyncore具有很大的优势,asyncore对原生的socket进行了封装,提供非常简洁优秀的接口,利用asyncore重写相关需要处理的接口,就可以完成一个socket的网络编程,从而不需要处理复杂的socket网络状况及多线程处理等等。
1)导入:import asyncore
2)定义类并继承自asyncore.dispatcherclass SocketClient(asyncore.dispatcher)
3).实现类中的回调代码def __init__(self,host,port)
4)创建对象并执行asyncore.loop
5) 其它回调函数:
def handle_connect(self):
print("连接成功")
def writable(self):
return True
# 实现handle_write回调函数
def handle_write(self):
#内部实现对服务器发送数据的代码
#调用send方法发送数据,参数是字节数据
self.send("hello ".encode('utf-8'))
def readable(self):
return True
def handle_read(self):
result = self.recv(1024)
print(result)
def handle_error(self):
# 编写处理错误的方法
t, e, trace = sys.exc_info()
print(e)
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'
...