【脚本编程系列】关于Python网络通讯asyncore,你需要知道的事

如何使用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模块实现异步通信方式,提供了用来构建异步通信方式的客户端和服务器端的基础架构。
尤其适合聊天类的服务器端和协议的实现。
其运行过程是创建一个或多个网络信道;当信道创建后,通过轮询方式来激活网络信道的服务,直到最后一个网络信道关闭。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值