如何終止用python寫的socket服務(wù)端程序?
問題描述
用python寫了一個socket服務(wù)端的程序,但是啟動之后由于監(jiān)聽連接的是一個死循環(huán),所以不知道怎樣在cmd運行程序的時候?qū)⑵浣K止。
#!/usr/bin/python# -*- coding: utf-8 -*-import socketimport threading, timedef 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’: breaksock.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都不能終止,請問要怎么終止程序?
問題解答
回答1:Ctrl + C
回答2:在啟動線程之前,添加 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 daemonthread (True) or not (False). This must be set before start() iscalled, otherwise RuntimeError is raised. Its initial value isinherited from the creating thread; the main thread is not a daemonthread and therefore all threads created in the main thread default todaemon = False.
The entire Python program exits when no alive non-daemon threads areleft.
這樣 <C-c> 的中斷信號就會被 rasie。
回答3:kill -9回答4:
關(guān)閉cmd命令窗口,重新開啟一個cmd,我是這么做的。
回答5:可以使用signal模塊,當按住Ctrl+C時,捕捉信息,然后退出.
#!/usr/bin/env python# -*- coding: utf-8 -*-import signaldef do_exit(signum, frame): print('exit ...') exit()signal.signal(signal.SIGINT, do_exit)while True: print('processing ...')回答6:
我記得可以
try: ......except KeyboardInterrupt: exit()
相關(guān)文章:
1. macos - mac下docker如何設(shè)置代理2. javascript - 學(xué)習(xí)網(wǎng)頁開發(fā),關(guān)于head區(qū)域一段腳本的疑惑3. javascript - JS設(shè)置Video視頻對象的currentTime時出現(xiàn)了問題,IE,Edge,火狐,都可以設(shè)置,反而chrom卻...4. angular.js - ng-grid 和tabset一起用時,grid width默認特別小5. javascript - 如何獲取未來元素的父元素在頁面中所有相同元素中是第幾個?6. Android下,rxJava+retrofit 并發(fā)上傳文件和串行上傳文件的效率為什么差不多?7. 熱切期待朱老師的回復(fù),網(wǎng)頁視頻在線播放器插件配置錯誤8. mysql - AttributeError: ’module’ object has no attribute ’MatchType’9. javascript - 從mysql獲取json數(shù)據(jù),前端怎么處理轉(zhuǎn)換解析json類型10. Whitelabel錯誤頁面發(fā)生意外錯誤(類型=未找到,狀態(tài)= 404)/WEB-INF/views/home.jsp
