并发网络通信-多进程

时间:2019-11-19 13:55:16   收藏:0   阅读:77

多进程
"""
多进程网络并发编程 TCP
"""
from socket import *
import os, signal


signal.signal(signal.SIGCHLD, signal.SIG_IGN)# 处理僵尸进程

 

def handle(cf):# 客户专用套接字处理客户信息(cf本身已经内涵客户端IP)
while True:
try:
data = cf.recv(1024)
except:
continue
if not data:
break
print(data.decode())
cf.send(b‘ok‘)
cf.close()

 

HOST = ‘0.0.0.0‘
PORT = 8888
ADDR = (HOST, PORT)
f = socket()# 建立套接字,绑定服务器ip port listen
f.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
f.bind(ADDR)
f.listen(5)
print(‘listen the port 8888...‘)
while True:
try:
cf, addr = f.accept()
print(‘connect from ‘, addr)
except KeyboardInterrupt:
os._exit(0)
except Exception as e:
print(e)
continue
# 创建子进程处理连接
pid = os.fork()
if pid == 0:
handle(cf)
f.close()
os._exit(0)
else:
cf.close()
continue

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!