码迷,mamicode.com
首页 > 系统相关 > 详细

多进程socket模型

时间:2015-07-06 13:50:56      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

每有一个客户端接入,服务端就生成一个进程对客户端提供服务,当客户端很多时,会消耗大量系统资源。

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()

多进程socket模型

标签:

原文地址:http://www.cnblogs.com/pylab/p/4624088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!