python之使用ctrl+c断开多线程(TcpSocketServer连接)出现端口占用的情况

1.使用setDaemon(True)代替join() 【全部替换】---不然子线程

2.在主线程

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    # 使用文件内容来判断是否关闭tcpsocketserver连接
    with open('文件路径','w') as f:
        f.write('0')
print('main end')

3.tcpsocketserver

def __init__(self, request, client_address, server):
    self.request = request
    self.client_address = client_address
    self.server = server
    self.setup()
    try:
        self.handle()
    finally:
        self.finish()

def setup(self):
    ip = self.client_address[0].strip()     # 获取客户端的ip
    port = self.client_address[1]           # 获取客户端的port
    print('ServerTCPForDev %s:%d is connected!' % (ip, port))

def handle(self):
    while True:
        with open('文件路径','r') as f:
            if int(f.read()) == 1:
                print('client tcp  ',self.client_address, ' 工作正常')
                # 给recv设置一个时间,如果超过了这个时间,就执行这个判断方法
                data = self.request.recv(1024)
                print('recv from client is %s' % data.decode())
            else:
                print('server',self.server, ' 即将断开连接' )
                self.server.shutdown() # 关闭服务端连接
                self.request.close()  # 关闭客户端连接
                break  
def finish(self):
    ip = self.client_address[0].strip()     # 获取客户端的ip
    port = self.client_address[1]           # 获取客户端的port
    print("tcp client(%s:%d) is disconnect!" % (ip, port))

客户端代码

import socket
import time
from threading import Thread

port = 10501

class ClientThread(Thread):
    def __init__(self):
        super(ClientThread, self).__init__()
    def run(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        try:
            while True:
                s.sendall('nihao'.encode('utf-8'))
                time.sleep(3)
        except:
            s.close()

for i in range(4):
    a = ClientThread()
    a.start()

作者:To be a cool guy
来源:CSDN
原文:https://blog.csdn.net/qq_32446743/article/details/80309836
版权声明:本文为博主原创文章,转载请附上博文链接!


2019-01-28,我用py开发的服务端,遇到tcpserver线程无法结束的问题,困扰了我好久,适逢公司搬迁,还有一些巧的无关的事项前来打扰。一拖3天多没有能解决这个问题。
今日早上,突然看到这篇,解我难题,在此感谢原博主

你可能感兴趣的:(python之使用ctrl+c断开多线程(TcpSocketServer连接)出现端口占用的情况)