如何从Python中的另一个线程中止socket.recv() [英] How do I abort a socket.recv() from another thread in Python

查看:389
本文介绍了如何从Python中的另一个线程中止socket.recv()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个等待连接的主线程.它产生客户端线程,这些线程将回显来自客户端的响应(在这种情况下为telnet).但是要说,我想在一段时间后关闭所有套接字和所有线程,例如1次连接之后.

I have a main thread that waits for connection. It spawns client threads that will echo the response from the client (telnet in this case). But say that I want to close down all sockets and all threads after some time, like after 1 connection.

我该怎么做?如果我从主线程执行clientSocket.close(),它不会停止执行recv.仅当我首先通过telnet发送某些内容时,它才会停止,然后它将无法进行进一步的发送和接收.

How would I do it? If I do clientSocket.close() from the main thread, it won't stop doing the recv. It will only stop if I first send something through telnet, then it will fail doing further sends and recvs.

我的代码如下:

# Echo server program
import socket
from threading import Thread
import time

class ClientThread(Thread):
    def __init__(self, clientSocket):
            Thread.__init__(self)
            self.clientSocket = clientSocket

    def run(self):
            while 1:
                    try:
                            # It will hang here, even if I do close on the socket
                            data = self.clientSocket.recv(1024)
                            print "Got data: ", data
                            self.clientSocket.send(data)
                    except:
                            break

            self.clientSocket.close()

HOST = ''
PORT = 6000
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverSocket.bind((HOST, PORT))
serverSocket.listen(1)

clientSocket, addr = serverSocket.accept()
print 'Got a new connection from: ', addr
clientThread = ClientThread(clientSocket)
clientThread.start()

time.sleep(1)

# This won't make the recv in the clientThread to stop immediately,
# nor will it generate an exception
clientSocket.close()

推荐答案

我知道这是一个老话题,塞缪尔(Samuel)可能很久以前就解决了他的问题.但是,我遇到了同样的问题,在Google'ing时碰到了这篇文章.找到了解决方案,并认为值得添加.

I know this is an old thread and that Samuel probably fixed his issue a long time ago. However, I had the same problem and came across this post while google'ing. Found a solution and think it is worthwhile to add.

您可以在套接字类上使用shutdown方法.它可以防止进一步发送,接收或同时阻止两者.

You can use the shutdown method on the socket class. It can prevent further sends, receives or both.

socket.shutdown(socket.SHUT_WR)

socket.shutdown(socket.SHUT_WR)

例如,以上内容阻止将来发送.

The above prevents future sends, as an example.

有关详细信息,请参阅Python文档.

这篇关于如何从Python中的另一个线程中止socket.recv()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆