标签:编程 多线程 主线程 hand sock threading 创建 from bind
多线程
"""
多线程网络网络并发编程 TCP
"""
from socket import *
from threading import Thread
import os
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
# 创建子线程处理连接
t = Thread(target=handle, args=(cf,))
t.setDaemon(True) # 分支线程随主线程结束而结束
标签:编程 多线程 主线程 hand sock threading 创建 from bind
原文地址:https://www.cnblogs.com/chenlulu1122/p/11888641.html