标签:
每有一个客户端接入,服务端就生成一个进程对客户端提供服务,当客户端很多时,会消耗大量系统资源。
from socket import *
import time
import os
import sys
def client_deal(client,client_info):
while True:
msg = client.recv(1024)
if msg == ‘‘:
client.close()
break
print ‘recv=‘,msg, ‘from:‘,client_info
client.send(‘echo‘+msg)
if msg ==‘q‘ or msg == ‘Q‘:
client.close()
break
def client_process(client,client_info):
pid = os.fork()
if pid == 0:
ppid = os.fork()
if ppid == 0:
client_deal(client,client_info)
else:
print ‘pid=‘,os.getpid()
sys.exit()
print "child exit"
else:
client.close()
os.wait()
print ‘Main process wait child exit‘
if __name__ == ‘__main__‘:
tcp_server = socket(AF_INET,SOCK_STREAM)
tcp_server.bind((‘localhost‘,5001))
tcp_server.listen(5)
while True:
print ‘pid=‘,os.getpid(),"wait client"
client,client_info = tcp_server.accept()
print client_info
client_process(client,client_info)
tcp_server.close()
标签:
原文地址:http://www.cnblogs.com/pylab/p/4624088.html