tinycodinglm / code /appdev-0045.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.61 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

Walk me through building a chat app: key concepts, concrete details and common pitfalls. Include a runnable code example with its expected output.

Assistant

WebSocket Chat App:

python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
import json

app = FastAPI()

class ConnectionManager:
    def __init__(self):
        self.active: list[WebSocket] = []

    async def connect(self, ws: WebSocket):
        await ws.accept()
        self.active.append(ws)

    def disconnect(self, ws: WebSocket):
        self.active.remove(ws)

    async def broadcast(self, message: str, sender: WebSocket):
        for conn in self.active:
            if conn != sender:
                await conn.send_text(message)

manager = ConnectionManager()

@app.websocket('/ws/{username}')
async def websocket_endpoint(websocket: WebSocket, username: str):
    await manager.connect(websocket)
    await manager.broadcast(f'{username} joined!', websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.broadcast(f'{username}: {data}', websocket)
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f'{username} left.', websocket)

HTML = '''
<h1>Chat</h1>
<input id="msg" type="text" placeholder="Type message...">
<button onclick="send()">Send</button>
<div id="log"></div>
<script>
const ws = new WebSocket(`ws://localhost:8000/ws/${prompt('Username:')}`);
ws.onmessage = (e) => {
    document.getElementById('log').innerHTML += `<p>${e.data}</p>`;
};
function send() {
    const msg = document.getElementById('msg');
    ws.send(msg.value); msg.value = '';
}
</script>'''

@app.get('/')
async def get():
    return HTMLResponse(HTML)

Run: uvicorn main:app --reload
Test: Open multiple browser tabs to http://localhost:8000