Different types Server in Python
来源:互联网 发布:js设置颜色渐变 编辑:程序博客网 时间:2024/06/08 17:34
multiprocess(The almost same as threading)
from socket import *from multiprocessing import *from time import sleepdef dealWithClient(newsocket,cAddr): while True: recvData = newsocket.recv(1024) if len(recvData)>0: print('----recv from %s ---- %s'%(str(cAddr),recvData)) else: print('The client is closed') break newsocket.close()def main(): sSocket = socket(AF_INET,SOCK_STREAM) Addr = ('',7788) sSocket.bind(Addr) sSocket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) sSocket.listen() try: while True: print('The server is waiting the client---') newSocket,cAddr = sSocket.accept() #replace the Process with Thread to convert it into multi thread client = Process(target=dealWithClient,args=(newSocket,cAddr)) client.start() newSocket.close() finally: sSocket.close()if __name__ == '__main__': main()
single process with no blocking
from socket import *import time#store all the connection still aliveg_socketList = []def main(): serSocket = socket(AF_INET,SOCK_STREAM) Addr = ('',7788) serSocket.bind(Addr) serSocket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) serSocket.listen() #set the server into unblocking to achieve multiple task solving serSocket.setblocking(False) while True: time.sleep(0.5) try: #if no client connect to server it will throws exceptions newClient = serSocket.accept() except Exception as result: pass else: g_socketList.append(newClient) print('---A new client connect to the server now ----%s'%str(newClient)) newClient[0].setblocking(False) for clien,cAddr in g_socketList: try: recvData =clien.recv(1024) if len(recvData)>0: print('Recv(%s)from(%s)'%(str(recvData),str(cAddr))) else: print('---client %s is closed---'%str(cAddr)) clien.close() g_socketList.remove((clien,cAddr)) except Exception as result: passif __name__ == "__main__": main()
select echo server
shortcoming:The client concurrent amount is small,1024(32bit machine)/2048(64 bit machine)
import selectfrom socket import *import sysserver = socket(AF_INET,SOCK_STREAM)server.bind(('',7788))server.listen()inputs = [server,sys.stdin]running = Truewhile True: readable,writeable,exceptional = select.select(inputs,[],[]) for sock in readable: if sock == server: conn , addr = server.accept() inputs.append(conn) elif sock == sys.stdin: cmd = sys.stdin.readline() running = False break else: data = sock.recv(1024) if data: sock.send(data) else: inputs.remove(sock) sock.close() if not running: breakserver.close()
epoll version server
Compared to select,it has no limit on the number of concurrent client
from socket import *import selects = socket(AF_INET,SOCK_STREAM)s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)s.bind(('',7788))s.listen(10)#create a epoll objectepoll = select.epoll()#fileno is file descriptorepoll.register(s.fileno(),select.EPOLLIN|select.EPOLLET)connections = {}address = {}while True: #process fd scanning epoll_list = epoll.poll() for fd,events in epoll_list: if fd == s.fileno(): conn,addr = s.accept() print('A new client is coming~ %s'%str(addr)) connections[conn.fileno()] = conn address[conn.fileno()] = addr epoll.register(conn.fileno(),select.EPOLLET|select.EPOLLIN) elif events == select.EPOLLIN: recvData = connections[fd].recv(1024) if len(recvData)>0: print('recv %s'%recvData) else: epoll.unregister(fd) connections[fd].close() print('----%s---offline----'%str(address[fd]))
Association(gevent) version server
import sysimport timeimport geventfrom gevent import socket,monkeymonkey.patch_all()def handle_request(conn): while True: data = conn.recv(1024) if not data: conn.close() break else: print('recv:',data) conn.send(data)def server(port): s = socket.socket() s.bind(('',port)) s.listen(5) while True: cli,addr = s.accept() gevent.spawn(handle_request,cli)if __name__=='__main__': server(7788)
阅读全文
1 0
- Different types Server in Python
- Different types of keystore in Java -- JKS
- Different types of keystore in Java -- PKCS12
- Different types of keystore in Java -- Overview
- Different Types of Switches in Networking
- Python built-in types - Numeric Types
- How to create different types of thread pool in Java
- Different types of thread-safe Sets in Java
- Different ways of associating known types in wcf
- Special Table Types In SQL Server
- Different ranking function in SQL Server
- Python: Why Use Built-in Types?
- Python built-in types - Truth Value Testing
- Python built-in types - repr(object)
- The different types of polymorphism in OOP-面向对象程序设计中的多态类型
- For different transaction types,What's the meaning of fields in MTL_MATERIAL_TRANSACTIONS
- 4.5 Using Different Types of Accessories in a Table View Cell
- Different sampler types for same sample texture unit in fragment shader.
- Windows下安装Ubuntu 16.04双系统(准备装,先收藏这个博客,写的不错)
- C++11四种强制类型转换
- 正则表达式基础用法
- 三分+贪心 [Ahoi2014]宅男计划
- 找到迷宫一条路的解
- Different types Server in Python
- 文章标题
- 使用ICMP协议检测网络状态
- PAT 甲级 1060. Are They Equal (25)
- (M)Dynamic Programming:357. Count Numbers with Unique Digits
- 删数问题(C语言实现)
- bzoj 1192: [HNOI2006]鬼谷子的钱袋
- 大三,2017下半年的计划
- < 笔记 > Python