Python(七)Socket编程、IO多路复用、SocketServer
2016-06-21 21:40
393 查看
本章内容:
Socket
IO多路复用(select)
SocketServer 模块(ThreadingTCPServer源码剖析)
socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求。
SocketServer.BaseRequestHandler
SocketServer的ThreadingTCPServer之所以可以同时处理请求得益于 select 和 Threading 两个东西,其实本质上就是在服务器端为每一个客户端创建一个线程,当前线程用来处理对应客户端的请求,所以,可以支持同时n个客户端链接(长连接)。
ForkingTCPServer
ForkingTCPServer和ThreadingTCPServer的使用和执行流程基本一致,只不过在内部分别为请求者建立 “线程” 和 “进程”。
基本使用:
Socket
IO多路复用(select)
SocketServer 模块(ThreadingTCPServer源码剖析)
Socket |
class BaseRequestHandler: """Base class for request handler classes. This class is instantiated for each request to be handled. The constructor sets the instance variables request, client_address and server, and then calls the handle() method. To implement a specific service, all you need to do is to derive a class which defines a handle() method. The handle() method can find the request as self.request, the client address as self.client_address, and the server (in case it needs access to per-server information) as self.server. Since a separate instance is created for each request, the handle() method can define arbitrary other instance variariables. """ def __init__(self, request, client_address, server): self.request = request self.client_address = client_address self.server = server self.setup() try: self.handle() finally: self.finish() def setup(self): pass def handle(self): pass def finish(self): pass
SocketServer.BaseRequestHandler
SocketServer的ThreadingTCPServer之所以可以同时处理请求得益于 select 和 Threading 两个东西,其实本质上就是在服务器端为每一个客户端创建一个线程,当前线程用来处理对应客户端的请求,所以,可以支持同时n个客户端链接(长连接)。
ForkingTCPServer
ForkingTCPServer和ThreadingTCPServer的使用和执行流程基本一致,只不过在内部分别为请求者建立 “线程” 和 “进程”。
基本使用:
#!/usr/bin/env python # -*- coding:utf-8 -*- import SocketServer class MyServer(SocketServer.BaseRequestHandler): def handle(self): pass if __name__ == '__main__': server = SocketServer.ForkingTCPServer(('127.0.0.1',8009),MyServer) server.serve_forever()
相关文章推荐
- Python 数据科学入门
- Python print 中的逗号小技巧
- python: pandas模块
- Python 深,浅copy
- python3X与python2X区别
- 【Python学习日记】字符编码
- Python的修饰器@
- 矩形裁剪算法_python3最终版
- 使用Mixin设计模式进行Python编程的方法讲解
- 详解Python中的from..import绝对导入语句
- python模块fileinput
- python模块fileinput
- 遍历python字典几种方法
- python 类的私有属性和方法
- python 字符串处理心得
- python中类的继承与方法重写
- 通过pyenv和virtualenv创建多版本Python虚拟环境
- python执行sql语句
- django在pyhton2.7 和 python3.* 之间代码和睦相处的方法
- Python的列表推导式