2016-04-14 150 views
0

我想監視一個SMB連接,我已經編寫了下面的代碼,但是我擔心我可能會綁定網絡。可以重複SMB套接字連接

以這種方式重複打開和關閉連接可以嗎?

import socket 
import time 
import threading 

class SMBConnectionMonitor(threading.Thread): 
    def __init__(self, host, poll_period=60, timeout=5): 
     super(SMBConnectionMonitor, self).__init__() 

     self.host = host 
     self.poll_period = poll_period 
     self.timeout = timeout 
     self.connected = False 
     self.stop_requested = False 

    def stop(self): 
     self.stop_requested = True 

    def run(self): 
     while not self.stop_requested: 
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
      sock.settimeout(self.timeout) 
      try: 
       sock.connect((self.host, 445)) 
       # successful, if this is the first time update the status 
       if not self.connected: 
        self.connected = True 
      except socket.error as e: 
       # can't connect, if this is first time update the status 
       if self.connected: 
        self.connected = False 
      sock.close() 

      # wait for the poll period before trying another connection 
      for i in range(self.poll_period): 
       if self.stop_requested: return 
       time.sleep(1) 

monitor = SMBConnectionMonitor("remote-computer", poll_period=10) 
monitor.start() 
monitor.join(timeout=30) 
monitor.stop() 

回答

1

打開和關閉這樣的連接,每秒一次即使通過撥號也會產生微不足道的流量。即使你完全消除了循環中的延遲,它對現代網絡的影響也會很小,可能不會引人注目。 Python的相對較慢的速度以及啓動TCP連接所固有的延遲意味着即使您嘗試過,您也無法通過重複打開和關閉一個連接來接近網絡。