在Python中实现单进程非阻塞服务器很方便,主要的思想就是把socket设置成非阻塞的模式,之后使用轮询的方式进行数据访问,少量的链接是ok的,但是客户端多了会损失效率,来看下实现
from socket import *
server = socket(AF_INET, SOCK_STREAM)
server.bind(("", 8080))
server.setblocking(False)
server.listen(10)
clientlist = []
print("server is running!")
while True:
try:
client, addr = server.accept()
except:
pass
else:
print("a new client: %s" % str(addr))
client.setblocking(False)
clientlist.append((client, addr))
for cSocket, cAddr in clientlist:
try:
recvData = cSocket.recv(1024)
except:
pass
else:
if recvData:
print("%s %s" % (str(cAddr), recvData))
else:
cSocket.close()
clientlist.remove((cSocket, cAddr))
print("%s exit" % (str(cAddr)))