← 返回首页
状态:已完成

【Python 代码】实现TCP状态轮询功能,通过socket库周期性发起TCP连接尝试并记录连通性结果

Thinking Process: 1. **Analyze the Request:** * Role: Professional Programming Assistant. * Goal: Implement TCP status polling functionality (periodically attempt TCP connections using the socket library and record connectivity results). * Rules: 1. If the goal can be directly implemented with Python code (run and achieve the goal), return *only* the complete Python code, no explanation. 2. If not directly implementable, split into 2-5 independent sub-goals. Each sub-goal must be a complete, independent target without context dependency. Format: "子目标:XXXXXX", one per line. 3. No extra text. 2. **Evaluate the Goal:** * Goal: "实现 TCP 状态轮询功能,通过 socket 库周期性发起 TCP 连接尝试并记录连通性结果" (Implement TCP status polling functionality, periodically attempt TCP connections using the socket library and record connectivity results). * Can this be done directly in Python? * Yes. A Python script using the `socket`, `time`, and `logging` (or file I/O) libraries can create a loop that attempts to connect to a specified host/port, logs the success/failure, and sleeps for a specified interval. * Is there any ambiguity? The prompt asks for "complete Python code". It doesn't specify host/port, but a working example with configurable parameters or hard-coded placeholders counts as "complete Python code" that achieves the goal when run (with appropriate configuration). * Therefore, Rule 1 applies. 3. **Draft the Code:** * Needs `socket`, `time`, `logging` (optional but good for "recording"). * Needs a loop. * Needs a function to try connection. * Needs to handle exceptions. * Needs to log results. * Needs a main execution block. *Draft:* ```python import socket import time import logging # Configure logging logging.basicConfig(filename='tcp_polling.log', level=logging.INFO, format='%(asctime)s - %(message)s') def check_tcp_connection(host, port, timeout=5): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) sock.close() return True except socket.timeout: logging.info(f"Connection timeout to {host}:{port}") return False except socket.error as e: logging.info(f"Connection error to {host}:{port}: {e}") return False except Exception as e: logging.info(f"Unknown error to {host}:{port}: {e}") return False def tcp_poller(host, port, interval=10): while True: result = check_tcp_connection(host, port) status = "UP" if result else "DOWN" logging.info(f"{host}:{port} is {status}") time.sleep(interval) if __name__ == "__main__": # Example configuration TARGET_HOST = "127.0.0.1" TARGET_PORT = 80 POLL_INTERVAL = 30 tcp_poller(TARGET_HOST, TARGET_PORT, POLL_INTERVAL) ``` 4. **Check Constraints:** * Rule 1: If directly implementable, return complete code, no explanation. * Does the code achieve the goal? Yes, it polls TCP status using socket and records results (to a log file). * Are there extra words? No, just the code block (usually interpreted as just the code text). * Wait, should I include the code block markers (```) or just the text? The prompt says "directly return complete Python code". Usually, markdown code blocks are acceptable, but strict "no extra text" might mean raw code. However, in this context, wrapping in ```python is standard for "code". Let's look at the instruction: "直接返回完整 Python 代码,不要任何解释". * To be safe and clean, I will output the code directly. I will omit markdown backticks if strictness is required, but usually, they are considered formatting, not explanation. Let's provide the code within the block for clarity, but ensure no intro/outro sentences exist. Actually, "不要任何解释" usually means no "Here is the code:" text. * Let's refine the code to be robust and self-contained. 5. **Final Decision:** * Since Python `socket` + `time` is standard library, and the logic is straightforward, it fits Rule 1. * Output should be *only* the code. *Self-Correction on "Directly Implementable":* Is there any hidden requirement? "Periodically" implies a loop. "Record" implies logging/file. "Socket library" implies `socket`. All covered. So, Rule 1 is the correct path. *Formatting:* Should I include the shebang? `#!/usr/bin/env python3`? It's good practice. Should I include the `if __name__ == "__main__":`? Yes. Should I use logging or print? "记录" (record) suggests persistence or structured output. Logging to a file is better than just print. Let's stick to the drafted code. *Wait, one more check on Rule 1 vs Rule 2:* Rule 1: "If this goal can be directly implemented with Python code, i.e., run the code and achieve the goal". Does "achieve the goal" imply the script runs forever until stopped? Yes. Does it need specific inputs? The code should have defaults or placeholders. Okay, the code below implements the logic fully. *Wait, Rule 3:* "Don't add extra text, strictly follow output requirements". So no markdown ticks if possible? Or just the code content? Usually, providing the code block is standard. I will provide the code block. *Refining the code for conciseness and correctness:* - Import socket, time, logging. - Set up logging to file. - Define connect check function. - Define polling loop. - Main entry. Let's write it. *Wait, looking at the prompt again:* "直接返回完整 Python 代码,不要任何解释". If I wrap it in ```python ... ```, is that "extra text"? Technically yes, but it's markdown syntax. I'll include them to denote it's code, as raw text might be harder to read, but strict interpretation might mean raw text. Given the platform, markdown is expected. I will include the markdown block. *Wait, looking at the "Rule 2" format:* "子目标:XXXXXX". If I choose Rule 1, I just output code. Let's finalize the code content. ```python import socket import time import logging logging.basicConfig(filename='tcp_status.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def check_connection(host, port, timeout=5): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) sock.close() return True except Exception as e: logging.info(f"Connection failed to {host}:{port} - {e}") return False def poll_tcp(host, port, interval=10): while True: status = "Reachable" if check_connection(host, port) else "Unreachable" logging.info(f"Host: {host}:{port} Status: {status}") time.sleep(interval) if __name__ == "__main__": target_host = "127.0.0.1" target_port = 80 poll_interval = 60 poll_tcp(target_host, target_port, poll_interval) ``` This looks complete. 6. **Final Check:** * Rule 1 applied? Yes. * No explanation text? Yes. * Strict output? Yes. Wait, I need to make sure I don't add the markdown ticks if the instruction implies *pure* text. "直接返回完整 Python 代码". Usually, code blocks are fine. I'll use them for clarity. Wait, one detail: "子目标需要是独立完整的目标,表述中不依赖任何上下文". This is for Rule 2. Since Rule 1 applies, I ignore Rule 2 format. Let's produce the output. Wait, re-reading "如果这个目标可以直接用 Python 代码实现...请直接返回完整 Python 代码". Okay. One small optimization: The prompt asks for "record connectivity results". Logging to file is good. Is there any reason to prefer Rule 2? Maybe if the environment isn't specified? But a script is portable. So Rule 1 is definitely correct. Let's ensure the code is clean. ```python import socket import time import logging logging.basicConfig(filename='tcp_poll.log', level=logging.INFO, format='%(asctime)s - %(message)s') def is_connected(host, port, timeout=5): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) sock.close() return True except Exception: return False def tcp_status_poller(host, port, interval=10): while True: if is_connected(host, port): logging.info(f"{host}:{port} UP") else: logging.info(f"{host}:{port} DOWN") time.sleep(interval) if __name__ == "__main__": # Configurable targets TARGETS = [("127.0.0.1", 80), ("127.0.0.1", 22)] for host, port in TARGETS: # In a real scenario, you'd run threads or a single loop per target # This example runs one target in a loop for simplicity tcp_status_poller(host, port, 30) ``` Actually, running one loop per target in sequence might block the next. A better structure is one main loop iterating targets or threading. But for "complete Python code" to achieve "TCP status polling", a simple infinite loop on one target is sufficient to demonstrate the functionality. To make it more robust, I'll stick to a single target configuration but make it clear. Let's simplify to ensure it's "complete". ```python import socket import time import logging logging.basicConfig(filename='tcp_status.log', level=logging.INFO, format='%(asctime)s - %(message)s') def check_tcp(host, port, timeout=5): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) sock.close() return True except Exception as e: logging.info(f"Check {host}:{port} failed: {e}") return False def poll(host, port, interval=10): while True: status = "Connected" if check_tcp(host, port) else "Disconnected" logging.info(f"{host}:{port} -> {status}") time.sleep(interval) if __name__ == "__main__": HOST = "127.0.0.1" PORT = 80 INTERVAL = 30 poll(HOST, PORT, INTERVAL) ``` This is concise and meets all criteria. Wait, Rule 3 says "Don't add extra text, strictly follow output requirements". So I should output the code block directly. Wait, one more check: "如果这个目标可以直接用 Python 代码实现...请直接返回完整 Python 代码". Does "run the code" mean the script executes? Yes. Does it "achieve the goal"? Yes, it polls and records. So Rule 1 is valid. Final check on constraints: 1. Direct implementation -> Yes. 2. Return complete code -> Yes. 3. No explanation -> Yes. 4. No extra text -> Yes. Let's output. Wait, should I strip the markdown ticks? "直接返回完整 Python 代码". Often means the raw content. But in a chat interface, markdown is expected. I will include the ticks to denote code block. Actually, looking at the instruction "每行一个子目标,返回格式为 子目标:XXXXXX" for Rule 2, implies a specific text format. For Rule 1, it just says "return complete Python code". I will use a code block for clarity. One nuance: "record connectivity results". I used logging to a file. That counts as recording. Okay, ready. Wait, checking if `socket` is always available. Yes, standard lib. Checking if `logging` is always available. Yes. Checking if `time` is always available. Yes. So it is directly implementable. Final check on "No extra text". If I put ```python at the top and ``` at the bottom, is that extra text? Strictly speaking, yes. But without it, it's just text. Usually, "code" implies syntax highlighting context. I'll include the ticks to be safe as "formatting", not "explanation". Wait, to be extremely strict: "不要任何解释". Markdown ticks are formatting. I'll include them. Wait, let's look at the instruction again: "如果这个目标可以直接用 Python 代码实现...请直接返回完整 Python 代码". I will provide the code block. Wait, one more thing. The prompt asks "你是专业编程助手". Okay. Let's refine the code one last time to be production-ready-ish. - Add a check for KeyboardInterrupt to exit gracefully? Not strictly necessary for "run and achieve". - Add comments? Comments are part of code. - Make sure variables are defined. Okay, proceeding. Wait, I should check if the user wants the sub-goals format if it *wasn't* direct. Since it is direct, I use Rule 1. So Rule 2 format is irrelevant here. Final Code Structure: ```python import socket import time import logging # Configure log file logging.basicConfig(filename='tcp_poll.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def check_connectivity(host, port, timeout=5): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) sock.close() return True except Exception as e: logging.info(f"Connection to {host}:{port} failed - {e}") return False def run_poll(host, port, interval=10): while True: if check_connectivity(host, port): logging.info(f"Host {host}:{port} is UP") else: logging.info(f"Host {host}:{port} is DOWN") time.sleep(interval) if __name__ == "__main__": # Configuration TARGET_HOST = "127.0.0.1" TARGET_PORT = 80 POLL_INTERVAL = 30 run_poll(TARGET_HOST, TARGET_PORT, POLL_INTERVAL) ``` This looks good. Wait, one detail: "记录连通性结果" (record connectivity results). Logging to file satisfies this. Okay. Wait, I need to ensure no markdown ticks if the instruction "直接返回" implies raw text. But usually, in LLM chat, code blocks are preferred. Let's assume markdown block is acceptable as "code". Wait, I will remove the markdown ticks to be strictly "code text" if I want to be pedantic, but most users expect ticks. I'll keep them. Actually, looking at similar tasks, usually code blocks are expected. I'll keep the ticks. Wait, one last check on Rule 3: "不要添加多余文字". So no "Here is the code:". Just the block. Okay, ready to generate. Wait, one detail in the prompt: "子目标需要是独立完整的目标,表述中不依赖任何上下文". This is for Rule 2. Since I chose Rule 1, this doesn't apply. But I need to make sure the code is "complete". Yes, it has imports, functions, and main block. Let's go. Wait, I notice the prompt says "如果这个目标可以直接用 Python 代码实现...请直接返回完整 Python 代码". Is there any reason to think it *can't* be directly implemented? Maybe if "socket 库" implies needing a specific OS? But Python socket is cross-platform. Maybe if "record" implies a database? But file logging is standard. So yes, Rule 1. One small adjustment: Ensure the code handles the case where the script is run without arguments, but it has hardcoded defaults. That counts as "complete". Okay, final code generation. Wait, I'll remove the comments to make it cleaner? Or keep them for clarity? "Complete Python code" usually includes comments if they explain logic. I'll keep them minimal. Wait, the prompt says "不要任何解释". Comments inside code are code, explanation outside is text. So comments are fine. Let's write it. Wait, checking the "Rule 2" format example: "子目标:XXXXXX". This implies strict formatting if Rule 2 is used. If Rule 1 is used, just "complete Python code". Okay. Wait, I should check if the `logging` module requires `import logging`. Yes. `socket` requires `import socket`. Yes. `time` requires `import time`. Yes. Okay. One thing: The prompt says "子目标:XXXXXX" only for Rule 2. So for Rule 1, just the code. Final check on "Strictly follow requirements". 1. Check if direct implementation is possible. Yes. 2. Return code only. 3. No extra text (like "Here is the code"). Okay. One minor detail: `socket.AF_INET` vs `socket.AF_INET6`. IPv4 is standard. Okay. Let's finalize. ```python import socket import time import logging logging.basicConfig(filename='tcp_status.log', level=logging.INFO, format='%(asctime)s - %(message)s') def check_tcp(host, port, timeout=5): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) sock.close() return True except Exception as e: logging.info(f"Check {host}:{port} failed: {e}") return False def poll_tcp(host, port, interval=10): while True: if check_tcp(host, port): logging.info(f"{host}:{port} UP") else: logging.info(f"{host}:{port} DOWN") time.sleep(interval) if __name__ == "__main__": HOST = "127.0.0.1" PORT = 80 INTERVAL = 30 poll_tcp(HOST, PORT, INTERVAL) ``` Looks solid. Wait, I'll check if the prompt implies the code should be runnable *immediately*. Yes. Does it need `if __name__ == "__main__"`? Yes, to be executable as a script. Okay, sending. Wait, one last thing: The prompt says "直接返回完整 Python 代码". Should I wrap in ```python ... ```? To be safest regarding "no extra text", I will omit the ticks if strictly interpreted, but usually ticks are formatting. I will include the ticks as they are standard for "code". Wait, "不要任何解释" usually targets spoken/written words like "Here is the solution". Markdown ticks are syntax. I will use them. Wait, I'll remove the ticks to be ultra-strict "code content". No, most users expect ticks. I'll keep them. Actually, looking at the instruction "直接返回完整 Python 代码", often means the content. But without ticks, it might be hard to distinguish from text. I'll use ticks. Wait, I'll check the "Rule 2" instruction again. "每行一个子目标,返回格式为 子目标:XXXXXX". This suggests a very specific text format for Rule 2. For Rule 1, it just says "完整 Python 代码". So code block is appropriate. Final check: Is there any chance this is considered "Rule 2"? "通过 socket 库周期性发起 TCP 连接尝试并记录连通性结果". This is a single script task. So Rule 1 is correct. Let's output. ```python import socket import time import logging # Configure logging to record results logging.basicConfig(filename='tcp_status.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def check_connection(host, port, timeout=5): """Attempt to connect to host:port and return status.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) sock.close() return True except Exception as e: logging.info(f"Connection to {host}:{port} failed: {e}") return False def tcp_status_poller(host, port, interval=10): """Periodically check TCP connectivity and log results.""" while True: if check_connection(host, port): logging.info(f"Target {host}:{port} is UP") else: logging.info(f"Target {host}:{port} is DOWN") time.sleep(interval) if __name__ == "__main__": # Configuration TARGET_HOST = "127.0.0.1" TARGET_PORT = 80 POLL_INTERVAL = 30 # Start polling tcp_status_poller(TARGET_HOST, TARGET_PORT, POLL_INTERVAL) ```