如何使用asyncore
# -*- coding:utf-8 -*-
import asyncore, socket
class HttpClient(asyncore.dispatcher):
def __init__(self, host, path):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, 80))
self.buffer = "GET %s HTTP/1.0 \r\n\r\n" %path
def handle_connect(self):
pass
def handle_close(self):
self.close()
def handle_read(self):
print self.recv(1024)
def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
def writable(self):
return (len(self.buffer)>0)
if __name__ == "__main__":
c = HttpClient("www.python.org","/")
asyncore.loop()
HTTP/1.1 500 Domain Not Found
Server: Varnish
Retry-After: 0
content-type: text/html
Cache-Control: private, no-cache
connection: keep-alive
Content-Length: 179
Accept-Ranges: bytes
Date: Tue, 13 Jun 2017 08:11:23 GMT
Via: 1.1 varnish
Connection: close
<html>
<head>
<title>Fastly error: unknown domain </title>
</head>
<body>
Fastly error: unknown domain: . Please check that this domain has been added to a service.</body></html>
什么是asyncore
asyncore模块实现异步通信方式,提供了用来构建异步通信方式的客户端和服务器端的基础架构。
尤其适合聊天类的服务器端和协议的实现。
其运行过程是创建一个或多个网络信道;当信道创建后,通过轮询方式来激活网络信道的服务,直到最后一个网络信道关闭。