可以重复进行SMB套接字连接吗

2024-04-23 07:07:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想监视一个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()

Tags: theimportselfhostiftimetimeoutsocket
1条回答
网友
1楼 · 发布于 2024-04-23 07:07:29

像这样每秒打开和关闭一次这样的连接,即使是通过拨号上网也会产生微不足道的流量。即使您完全消除了环路中的延迟,它对现代网络的影响也很小,甚至可能不明显。Python相对较慢的速度加上启动TCP连接所固有的延迟意味着即使您尝试了,也无法通过反复打开和关闭一个连接来接近于捆绑网络。在

相关问题 更多 >