简体   繁体   English

用开放连接退出Python套接字客户端吗?

[英]Quitting Python socket client with open connection?

The following script receiving data from a socket connection does not react to the CTRL+C signal sent in order to exit: 以下脚本从套接字连接接收数据不会响应为退出而发送的CTRL + C信号:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
"""
import socket
HOST = '192.168.178.1'
PORT = 1012
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while 1:
    data = s.recv(1024)
    print 'Received', repr(data)
s.close()

How can the program be modified so that program input or the default signal causes the infinite loop to be broken in order to end the program gracefully? 如何修改程序,以便程序输入或默认信号导致无限循环中断,以便正常结束程序?

Use Select 使用选择

import socket
import select

HOST = '192.168.178.1'
PORT = 1012
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(1)
s.connect((HOST, PORT))
time_out=None
ready=[[s],[],[], time_out]

if ready:
   s.recv(1024)

s.close()

One solution is to close the socket from another thread as shown by S. Prasanna in his blog article . 一种解决方案是从另一个线程关闭套接字,如S. Prasanna在其博客文章中所示 Another may be to catch the signal somehow. 另一个可能是以某种方式捕获信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM