并发网络通信-多进程

多进程
"""
多进程网络并发编程 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

猜你喜欢

转载自www.cnblogs.com/chenlulu1122/p/11888637.html