どう

2017-07-21 5 views
0

私のスクリプトは、このように動作します非クラスからクラスのソケットを閉じます:どう

# other part of code 

class request(threading.Thread): 

    def __init__(self): 
     threading.Thread.__init__(self) 

    def run(self): 
     while True: 
     try: 
       socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
       socket.connect((host), (port)) 
       socket.send(str.encode("test")) 
      except: 
       socket.close() 

def loop(): 
    for x in range(5): 
     request(x).start() 

# other 
# part 
# of code 

def startall(): 
    # some other code 
    choice = input("command: ") 
    if choice == "request": 
     loop() 
    elif choice == "stop": 
     # ? 
    # some other code 

startall() 

入力が「停止」の場合は、要求の送信を停止する方法はありますか?これは単なるサンプルであり、私のスクリプトはこのように動作しないことに注意してください。

class request(threading.Thread): 
     REQUESTS_ALLOWED = True 

    def run(self): 
     while request.REQUESTS_ALLOWED: 
      socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
      try: 
       socket.connect((host), (port)) 
       socket.send(str.encode("test")) 
      except: 
       pass # Do what you need 
      finally: 
       socket.close() 

お知らせソケットを閉じるの交代:私はちょうどあなたがfolowsようにクラスを変更することができ、一度にすべての要求を停止する場合は、あなたが私の問題

答えて

1

であるかを理解できるように、このコードを置きます。あなたのコードでは、ガベージコレクタが変数socketを破棄したときにソケットが閉じられました。私の代わりに、すべての反復でソケットが閉じられていることが保証されています。

startstopイベントは、すべてのrequestオブジェクトの状態を変更できるようになりました。

if choice == "request": 
    request.REQUESTS_ALLOWED = True 
    loop()   
elif choice == "stop": 
    request.REQUESTS_ALLOWED = False 

FalseREQUESTS_ALLOWEDを設定した後、あなたはjoin()すべてのスレッドを実行している必要があります。通常、関数が返されたときに何かが行われたことを示しているので、これはちょうどお勧めです(それを行う必要はありません)。関数startall()から返された後、choice = "stop"は、開始されたすべてのスレッドが停止すると予想します。

完全なコード例:

import threading 
import time 

class Request(threading.Thread): 
    REQUESTS_ALLOWED = True 
    active_threads = set() 

    def __init__(self): 
     threading.Thread.__init__(self) 

    def start(self): 
     Request.active_threads.add(self) # Add thread to set for later use 
     super().start() 

    def run(self): 
     while Request.REQUESTS_ALLOWED: 
      print("Thread {} is alive.".format(self.name)) 
      time.sleep(1) 
     print("Thread {} is done.".format(self.name)) 

def loop(): 
    for x in range(5): 
     Request().start() 

def startall(choice): 
    if choice == "request": 
     Request.REQUESTS_ALLOWED = True 
     loop() 
    elif choice == "stop": 
     Request.REQUESTS_ALLOWED = False 
     # Iterate through active threads and wait for them 
     for thread in Request.active_threads: 
      thread.join() 
     Request.active_threads.clear() 

startall("request") 
time.sleep(3) 
startall("stop") 

コードは、動作するようには思えないのPython 3.6.1

+0

で試験しました。終了したスレッドにすべて参加しなければならないと言った...どうすればいいですか?すべてのアクティブなリクエスト/スレッドを停止する必要がありますか? – AllExJ

+0

@AllExJ私はそれが助けてくれることを願って答えを広げた。 – Qeek

+0

それは動作します!ありがとう!!! – AllExJ