如何终止用python写的socket服务端程序?

 秋知落叶冷 发布于 2022-10-25 11:25

用python写了一个socket服务端的程序,但是启动之后由于监听连接的是一个死循环,所以不知道怎样在cmd运行程序的时候将其终止。

#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import threading, time

def tcplink(sock,addr):
    print('Accept new connection from %s:%s...' %addr)
    sock.send(b'Welcome!')
    while True:
        data=sock.recv(1024)
        time.sleep(1)
        if not data or data.decode('utf-8')=='exit':
            break
        sock.send(('Hello,%s!'% data.decode('utf-8')).encode('utf-8'))
    sock.close()
    print('Connection from %s:%s closed.' % addr)
    
s=socket.socket()
s.bind(('127.0.0.1',1234))
s.listen(5)
print('Waiting for conection...')

while True:
    #accept a new connection
    sock,addr=s.accept()
    #create a new thread
    t=threading.Thread(target=tcplink,args=(sock,addr))
    t.start()

在win10上的cmd运行后的情况是按ctrl+c,ctrl+z,ctrl+d都不能终止,请问要怎么终止程序?

6 个回答
  • 我记得可以

    try:
        ......
    except KeyboardInterrupt:
        exit()
    2022-10-26 23:17 回答
  • 可以使用signal模块,当按住Ctrl+C时,捕捉信息,然后退出.

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import signal
    
    def do_exit(signum, frame):
        print("exit ...")
        exit()
    
    signal.signal(signal.SIGINT, do_exit)
    
    while True:
        print("processing ...")
    
    2022-10-26 23:18 回答
  • 关闭cmd命令窗口,重新开启一个cmd,我是这么做的。

    2022-10-26 23:18 回答
  • kill -9
    2022-10-26 23:18 回答
  • 在启动线程之前,添加 setDaemon(True)

    while True:
        #accept a new connection
        sock,addr=s.accept()
        #create a new thread
        t=threading.Thread(target=tcplink,args=(sock,addr))
        t.setDaemon(True)  # <-- add this
        t.start()
        
    

    daemon

    A boolean value indicating whether this thread is a daemon
    thread (True) or not (False). This must be set before start() is
    called, otherwise RuntimeError is raised. Its initial value is
    inherited from the creating thread; the main thread is not a daemon
    thread and therefore all threads created in the main thread default to
    daemon = False.

    The entire Python program exits when no alive non-daemon threads are
    left.

    这样 <C-c> 的中断信号就会被 rasie。

    2022-10-26 23:18 回答
  • Ctrl + C

    2022-10-26 23:18 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有