在本地两个端口测试了下,可以
server: hello.py
process版
#!/usr/bin/python3
import os, sys
from socket import *
import signal
ADDR = ('127.0.0.1', int(sys.argv[1]))
BUFFERSIZE = 1024
tcp = socket(AF_INET, SOCK_STREAM)
tcp.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
tcp.bind(ADDR)
tcp.listen(4)
def handle(cli):
addr = cli.getpeername()
while True:
data = cli.recv(1024).decode('utf-8')
if data=='':
# cli提前关闭的情况
break
print(cli.getpeername(),':',data)
reply = 'tks:'+data
cli.send(reply.encode('utf-8'))
# 关闭cli socket
cli.close()
sys.exit('cli'+str(addr)+'exit')
# 处理子进程,避免僵尸进程
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
while True:
try:
# 突然发现语句块内的变量同样也是全局变量,但这里多进程没关系
cli, addr = tcp.accept(