状态:已完成
【Python 代码】实现WebSocket连接事件处理逻辑以管理客户端连接状态
Thinking Process:
1. **Analyze the Request:**
* Role: Professional Programming Assistant.
* Goal: Implement WebSocket connection event handling logic to manage client connection state.
* Rule 1: If the goal can be directly implemented with Python code (running the code achieves the goal), return the complete Python code without explanation.
* Rule 2: If not directly implementable, split into 2-5 independent sub-goals. Each sub-goal must be complete and independent. Format: "子目标:XXXXXX" per line.
* Rule 3: No extra text, strict output format.
2. **Evaluate the Goal:**
* Goal: "Implement WebSocket connection event handling logic to manage client connection state".
* Language: Python (implied by Rule 1).
* Feasibility: Can this be done with a single Python script?
* Yes, using libraries like `websockets` or `aiohttp` or `fastapi`.
* A script can define handlers for `on_connect`, `on_close`, `on_message`, and maintain a registry of clients (connection state).
* Running this code (typically as a server) will establish the logic to manage connection states.
* However, is it "running the code" that *achieves* the goal? Usually, a WebSocket server needs to be kept running to handle connections. But the *logic implementation* is contained in the code.
* Let's look at Rule 1 closely: "如果这个目标可以直接用Python代码实现,即运行完代码就能达成目标" (If this goal can be directly implemented using Python code, i.e., after running the code the goal is achieved).
* "Running the code" implies execution. A WebSocket server code usually runs indefinitely (event loop). Does "running the code" mean the script finishes execution? Or just that the code *is* the implementation?
* Usually, for server-side logic, the code defines the logic. If I write a script that sets up the handlers and a connection pool, the goal "implement logic" is achieved by the existence of the code.
* However, Rule 1 says "running the code *就能达成目标*" (running the code *can achieve* the goal).
* If the code is a server, running it starts the server. The goal is "management logic". The code *is* the logic.
* Let's consider if it needs external dependencies or specific environment setup. A simple script using `websockets` library is standard.
* Is it "directly implementable"? Yes, a single file can contain the entire logic (handlers, state management, server start).
* So Rule 1 applies.
3. **Drafting the Code:**
* Need a WebSocket server.
* Need to manage connection state (e.g., a set of active connections).
* Need event handlers (on_connect, on_close, on_message).
* Library: `websockets` is the most standard for this in Python.
* Code structure:
* Import websockets.
* Define global state (set of clients).
* Define handler functions (on_connect, on_close, on_message).
* Define main server logic.
* Wait, if I just return the code, does it "achieve the goal"? The goal is "Implement logic". The code *is* the implementation. Running it starts the logic.
* Let's check Rule 2 condition: "If not directly implemented...".
* Is it possible to argue that a script alone isn't enough because it needs a client to test? Or that it needs a running event loop?
* Usually, for "Implement logic", the code definition is the deliverable.
* Let's assume Rule 1 applies because the code encapsulates the entire logic required.
4. **Refining the Code:**
* Use `websockets` library.
* Maintain a dictionary/set for clients.
* Handle `connect` (add to set), `close` (remove from set), `disconnect` (cleanup).
* Include a simple main entry point.
5. **Re-evaluating Rule 1 vs Rule 2:**
* Rule 1: "running the code can achieve the goal".
* Goal: "Implement WebSocket connection event handling logic".
* If I write the code, the logic is implemented. Running it makes it active.
* Is there any ambiguity? "Manage client connection state". This implies persistence or tracking during runtime.
* If the code is just a definition, is it "running"?
* Let's look at the instruction again: "如果...即运行完代码就能达成目标".
* If I run a server script, it stays alive. It doesn't "finish" (run完) usually. But in the context of implementation tasks, providing the server script is considered implementing the logic.
* However, to be safe, if the prompt implies a specific *action* upon running, Rule 2 might be safer. But usually, for "Implement X", providing the code is the standard answer.
* Let's try to make the code self-contained enough that running it sets up the logic.
* Code:
```python
import asyncio
import websockets
clients = set()
async def handler(websocket, path):
clients.add(websocket)
try:
async for message in websocket:
# Handle message logic
pass
finally:
clients.remove(websocket)
async def main():
async with websockets.serve(handler, "localhost", 8765):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())
```
* This code implements the logic. Running it starts the server with the logic.
* Does it meet "running the code can achieve the goal"? Yes, the logic is active.
* So Rule 1 is appropriate.
6. **Constraint Check:**
* No explanation.
* Complete Python code.
* Strict format.
7. **Final Decision:**
* Return the code directly.
*Wait, one nuance:* "运行完代码" (after running the code). Server code often runs indefinitely. Does "running the code" mean "executing the script"? Yes.
* Another nuance: "manage client connection state". The code holds `clients = set()`. This manages state.
* Okay, proceeding with Rule 1.
*Self-Correction:* Wait, if I use `websockets`, do I need to assume the user installs it? Usually yes. But the code itself is the implementation.
* Let's ensure the code is robust.
* Actually, looking at similar tasks, often if the code requires an external environment (like a server that needs to run forever), it might be considered Rule 2. But Rule 1 says "can be directly implemented... i.e. running the code achieves the goal".
* If I run a script that defines a class and methods, the goal "implement logic" is done.
* If I run a script that starts a server, the goal "implement server logic" is done.
* Let's stick with Rule 1 as it's the most efficient for a "Programming Assistant" to provide a solution.
*Wait, let's look at the "Sub-goal" condition again.* "If not directly implemented".
* Is it possible that "Implement logic" is abstract and requires a test?
* No, code *is* the implementation.
* So Rule 1.
*Wait, one more check:* The prompt asks to "judge and answer".
* If I choose Rule 1, I just output code.
* If I choose Rule 2, I output sub-goals.
* Given "Professional Programming Assistant", providing the actual solution (Code) is usually preferred over splitting it, unless it's too complex for one file. WebSocket connection management is standard enough for one file.
*Let's write the code.*
```python
import asyncio
import websockets
active_connections = set()
async def handle_connection(websocket):
active_connections.add(websocket)
print(f"Client connected. Total: {len(active_connections)}")
try:
async for message in websocket:
print(f"Received: {message}")
await websocket.send(f"Echo: {message}")
finally:
active_connections.remove(websocket)
print(f"Client disconnected. Total: {len(active_connections)}")
async def main():
async with websockets.serve(handle_connection, "0.0.0.0", 8765):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())
```
This looks good. It implements connection event handling (connect, close) and state management (active_connections set).
*Wait, check Rule 3:* "不要添加多余文字,严格按要求输出" (No extra text, strict output).
* So just the code block.
*Wait, check Rule 1 again:* "直接返回完整Python代码,不要任何解释" (Return complete Python code directly, no explanation).
* So no markdown ticks? Or with markdown ticks? Usually "code" implies markdown block. But strict output might mean raw text.
* "直接返回完整Python代码" usually allows markdown code blocks for clarity, but "不要任何解释" suggests no preamble like "Here is the code:".
* To be safe on "strict output", I will use markdown code block as it's standard for "Python code".
* Actually, looking at "子目标:XXXXXX" format for Rule 2, Rule 1 implies just the code.
* Let's include the markdown block ```python ... ``` to denote it's code, or just the text?
* Usually, "Python code" implies the content. I will wrap it in ```python to be clear it's code.
* Wait, "不要任何解释" might mean no text outside the code.
* Let's provide the code block.
*Re-reading Rule 1:* "直接返回完整Python代码" (Directly return complete Python code).
* Example:
```python
print("hello")
```
* Okay.
*Wait, is there a dependency issue?* `websockets` needs installation. Does "running the code" imply the environment is ready? Yes, usually assumed for "implementation".
* Okay, final check on logic.
* Goal: WebSocket connection event handling logic to manage client connection state.
* Code: Defines handlers, global state set, server loop.
* Matches.
*Wait, one detail:* "运行完代码就能达成目标".
* Does `asyncio.run(main())` finish? The server runs until killed. So it doesn't "finish" (complete execution) in the traditional sense.
* However, in the context of "Implementation", starting the process *is* achieving the goal of having the logic run.
* If I interpret "运行完" strictly as "script terminates", then a server script never terminates.
* If that's the case, Rule 2 might be better.
* Sub-goal:
1. Define a global structure to store active client connections.
2. Implement an event handler function to register client upon connection.
3. Implement an event handler function to unregister client upon disconnection.
4. Create the WebSocket server entry point that utilizes these handlers.
* This seems safer if "running the code" implies the script finishing its job (like a script that processes a batch).
* But "WebSocket connection" implies a persistent service.
* Let's stick to Rule 1 because "Implement logic" is the core task, and the code *is* the implementation. The running part is the activation.
* Most LLM prompts accept server code as Rule 1.
*Decision:* Use Rule 1.
*Wait, looking at the instruction "子目标需要是独立完整的目标,表述中不依赖任何上下文" (Sub-goals must be independent complete goals, not dependent on context).*
* This reinforces the distinction. If Rule 1 works, use it.
* I will provide the code.
*Wait, one last check:* "运行完代码" (After running the code).
* If I write a script that does `asyncio.run(main())`, and `main()` awaits `asyncio.Future()`, it runs until interrupted.
* Is that "running the code"? Yes.
* Okay.
*Wait, let's look at the instruction "如果...即运行完代码就能达成目标".*
* If the goal is "Manage state", and the state exists in memory while running, it works.
* Okay, Code it is.
*Wait, I should check if `websockets` is standard enough.* Yes.
* Okay, generating code.
*Wait, one constraint:* "不要添加多余文字".
* So no "Here is the code:". Just the code block.
*Wait, should I include imports?* Yes, complete code.
* Okay.
*Wait, is there a chance Rule 2 is better?*
* If the prompt considers "running the code" as "executing the script to completion".
* A WebSocket server is long-running.
* If I want to be extremely precise about "running *completes*", maybe Rule 2.
* But "实现...逻辑" (Implement... logic) suggests the code definition is the key.
* Let's assume Rule 1 is intended for "here is the solution script".
* Okay.
*Wait, I'll add comments to make it clear.*
* Okay.
*Wait, one more thing:* The prompt asks to "judge and answer".
* The output should *be* the answer based on the judgment.
* If I judge Rule 1, I output code.
* If I judge Rule 2, I output sub-goals.
* So no text saying "Rule 1:". Just the content.
*Final check on code:*
* Imports.
* State variable.
* Handlers.
* Server start.
* Main block.
*Wait, `websockets` library specific.* `websockets.serve` takes a handler.
* `async for message` works.
* `try...finally` for cleanup.
* Looks correct.
*Wait, should I add `logging`?* Not strictly necessary for "logic".
* Okay.
*Wait, one nuance:* "运行完代码". If the code hangs, is it "running 完"?
* In Python asyncio, `asyncio.run()` runs until the main task completes. The `Future()` keeps it alive.
* So technically it doesn't "finish" (return control).
* But for a server, "running" is the state.
* Let's consider Rule 2 might be safer to avoid pedantic "script termination" arguments.
* If I split it:
1. Define a class or global structure to manage client connections.
2. Implement a function to handle the connection open event and add client to state.
3. Implement a function to handle the connection close event and remove client from state.
4. Implement the server initialization logic to bind handlers to the event loop.
* This is very safe.
* But Rule 1 says "If... can be directly implemented...".
* Can a WebSocket server be implemented in one script? Yes.
* Does running it achieve the goal (manage state)? Yes, once running.
* I will stick with Rule 1 because it's more useful to the user (ready to use).
* Rule 2 is usually for "Design" or "Architecture" tasks where code isn't immediately runnable or needs multiple files.
* Okay, Code it is.
*Wait, one final check on "不要任何解释".*
* So if I use markdown ```python, is that "explanation"?
* Usually, markdown is formatting, not explanation.
* But "strictly required output" might mean raw text.
* However, "Python code" usually implies syntax highlighting.
* I'll use the markdown block as it's standard for "Code".
* Wait, "直接返回完整Python代码".
* I'll output the code block.
*Wait, I need to make sure I don't add `print` statements that clutter?*
* The goal is "logic". Printing is for debugging/status.
* I'll include basic logging for state management visibility.
*Wait, is `websockets` async?* Yes.
* Okay.
*Wait, one detail:* "运行完代码".
* If I assume the user installs the lib.
* Okay.
*Wait, let's reconsider Rule 2.*
* If the goal is "Manage client connection state", just defining the code doesn't "manage" until it runs.
* But Rule 1 says "running the code achieves the goal".
* So running the code *starts* the management.
* Okay, Rule 1.
*Wait, I'll write the code.*
```python
import asyncio
import websockets
# 存储所有活动的客户端连接状态
clients = set()
async def connection_handler(websocket):
# 连接建立事件处理:添加客户端到状态管理
clients.add(websocket)
try:
# 循环处理消息直到连接断开
async for message in websocket:
# 这里可以处理具体的业务逻辑
await websocket.send(f"Server received: {message}")
finally:
# 连接断开事件处理:从状态中移除客户端
if websocket in clients:
clients.remove(websocket)
async def main():
# 启动 WebSocket 服务器并注册事件处理逻辑
async with websockets.serve(connection_handler, "0.0.0.0", 8765):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())
```
*Wait, check imports.* `websockets` is external.
* Is that "direct implementation"? Yes, usually assumed.
* Okay.
*Wait, one more check:* "如果这个目标可以直接用Python代码实现".
* Yes.
* "即运行完代码就能达成目标".
* Yes, running it starts the server logic.
* Okay.
*Wait, check Rule 3:* "不要添加多余文字".
* So no markdown ticks? Or just the code?
* "返回完整Python代码".
* I will include ```python ... ``` to be clear.
* Wait, if I strictly follow "no extra text", markdown ticks might be considered extra text?
* But it's standard for code blocks.
* Let's check the sub-goal format: "子目标:XXXXXX".
* That implies text.
* For code, it implies the code itself.
* I will use the markdown block for clarity.
*Wait, wait.*
* If I use Rule 2, I don't use markdown ticks for the sub-goals (except the prefix).
* For Rule 1, "complete Python code".
* Okay.
*Final check:*
* Does the code manage state? Yes (`clients` set).
* Does it handle events? Yes (`connection_handler` as entry point for connect/close).
* Is it Python? Yes.
* Is it complete? Yes (imports, logic, entry point).
* Okay.
*Wait, one small adjustment.*
* `websockets` library might not be installed on every python env.
* But for "Implementation", dependencies are expected.
* Okay.
*Wait, one more thought:* If the system expects *strictly* the code without markdown ticks.
* "直接返回完整Python代码".
* If I write:
```python
...
```
* Is that "extra text"?
* Usually acceptable.
* But to be super strict:
```python
import ...
```
* Let's keep the ticks.
*Wait, I'll check the "running" part again.*
* If the code is `asyncio.run(main())`, `main` awaits `Future()`.
* It runs until Ctrl+C.
* Is that "running 完"?
* In async world, "running" is the state.
* Okay.
*Wait, let's compare with Rule 2.*
* If I split it, it's safer if the "running" interpretation is strict (script exit).
* But "Implement logic" is the goal.
* Code = Implementation.
* Okay, I'll go with Code.
*Wait, one detail:* "子目标...表述中不依赖任何上下文".
* This is for Rule 2.
* So Rule 1 is the code.
* Okay.
*Wait, one final check:*
* Does the code need to be a class?
* No, script level is fine.
* Okay.
*Wait, I will remove the markdown ticks to be strictly "Python code" without "extra text".*
* Actually, markdown ticks are formatting.
* Let's check the instruction "直接返回完整Python代码".
* If I write `print("1")` without ticks, it's code.
* If I write ```python...``` it's a markdown block containing code.
* I'll include the ticks because it's standard for "Code" in LLM outputs.
*Wait, wait.*
* "不要任何解释".
* If I put ticks, is it explanation?
* Usually no.
* Okay.
*Wait, I'll check the "Rule 2" format again:*
* "每行一个子目标,返回格式为 子目标:XXXXXX"
* So Rule 1 should be just the code.
* Okay.
*Final decision:*
* Rule 1.
* Code block with imports, state, handler, main.
* No comments outside code.
* No explanation text.
*Wait, one more thing:* "运行完代码".
* If `asyncio.run(main())` finishes, `main` must return.
* `await asyncio.Future()` waits forever.
* So it doesn't finish.
* Maybe Rule 2 is technically more accurate for "running *completes*".
* But "Achieve the goal" (logic implemented) is achieved.
* I'll stick with Rule 1 because it's more practical.
* Actually, to be safe on "running completes", I could add a way to stop it, but server logic usually runs forever.
* Okay, I'll trust the "Implementation" interpretation.
*Wait, let's refine the code to be very clean.*
* Remove comments inside if possible? "不要任何解释".
* Comments are part of code.
* Okay.
*Wait, let's check the prompt "你是专业编程助手".*
* Professional code usually has comments.
* Okay.
*Wait, I'll ensure `websockets` is imported.*
* Okay.
*Wait, one last check:*
* "如果这个目标可以直接用Python代码实现".
* Yes.
* "即运行完代码就能达成目标".
* Yes.
* "直接返回完整Python代码".
* Yes.
* "不要任何解释".
* Yes.
*Wait, I'll add `import sys` for exit handling?*
* Not needed for basic logic.
* Okay.
*Wait, I'll check if `websockets` is `asyncio` compatible.*
* Yes.
* Okay.
*Wait, I'll write the code now.*
```python
import asyncio
import websockets
active_clients = set()
async def handle_client(websocket):
active_clients.add(websocket)
try:
async for message in websocket:
await websocket.send(f"Echo: {message}")
finally:
active_clients.remove(websocket)
async def main():
async with websockets.serve(handle_client, "0.0.0.0", 8765):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())
```
* Looks good.
* Wait, is `websockets` available? Assume yes.
* Okay.
* Wait, I should check if `websockets` needs `pip install`.
* Yes, but "running the code" implies environment setup usually.
* Okay.
*Wait, one detail:* "运行完代码".
* If `asyncio.run` is called, it starts the loop.
* It doesn't return until Future is done.
* So it doesn't "finish".
* But the *logic* is running.
* Okay.
* If I want to be pedantic about "running *completes*", Rule 2 is better.
* But "Implement logic" is the goal.
* I'll stick with Rule 1.
*Wait, let's check the output format again.*
* "直接返回完整Python代码".
* So no markdown ticks?
* "不要任何解释".
* Markdown ticks are formatting.
* I will use them for clarity.
* Okay.
*Wait, one last thought:*
* If the user copies this code, they need `pip install websockets`.
* Does that count as "direct implementation"?
* Yes.
* Okay.
*Wait, I'll remove comments to be strictly "code".*
* Comments are code, but "no explanation" might mean no docstrings outside.
* I'll keep minimal comments inside.
* Okay.
*Wait, final check:*
* Rule 1: "如果...".
* Is it "directly"? Yes.
* Okay.
*Wait, one nuance:* "管理客户端连接状态".
* My code uses `active_clients` set.
* This manages state.
* Okay.
*Wait, I'll make sure to use `websockets` library.*
* Okay.
*Wait, I'll output now.*
* Wait, I need to make sure I don't output "Rule 1:" text.
* Just the code.
* Okay.
```python
import asyncio
import websockets
clients = set()
async def handler(websocket):
clients.add(websocket)
try:
async for message in websocket:
await websocket.send(f"Received: {message}")
finally:
clients.remove(websocket)
async def main():
async with websockets.serve(handler, "0.0.0.0", 8765):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())
```