C.W.K.
Stream
Lesson 03 of 08 · published

Echo 서버

~10 min · fastapi, echo, html-test-page

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

완전한 loopback 서버

이전 두 lesson 묶기: 모든 message 를 작은 envelope (timestamp, server name, type) 으로 감싸고 같은 FastAPI 앱에서 작은 HTML 테스트 페이지를 / 에서 serve 하는 echo 서버. application logic 짜는 동안 sanity-check sandbox 로 유용.

HTML 페이지 왜

브라우저는 https:// 페이지에서 ws:// reject 하고, 많은 corporate proxy 가 raw ws:// 자체를 막아. 같은 origin 에서 테스트 클라 serve 하면 둘 다 회피. cwkPippa 가 같은 트릭 — 개발 중 React UI 와 FastAPI backend 가 인접 포트, production deploy 는 single origin 에 박아.

Code

Self-contained echo + 테스트 페이지·python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
from datetime import datetime

app = FastAPI()

@app.websocket('/ws')
async def echo(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_json({
        'type': 'system',
        'message': 'connected to echo',
        'ts': datetime.now().isoformat(),
    })
    try:
        async for msg in websocket.iter_json():
            await websocket.send_json({
                'type': 'echo',
                'original': msg,
                'ts': datetime.now().isoformat(),
                'server': 'fastapi-echo-v1',
            })
    except WebSocketDisconnect:
        # Client closed; nothing to clean up here yet.
        pass

@app.get('/')
async def index():
    return HTMLResponse('''
<!doctype html><html><body>
<input id=msg placeholder="type and Enter">
<pre id=log></pre>
<script>
  const log = document.getElementById('log');
  const ws = new WebSocket('ws://' + location.host + '/ws');
  ws.onmessage = e => log.textContent += e.data + '\n';
  document.getElementById('msg').addEventListener('keydown', e => {
    if (e.key === 'Enter') {
      ws.send(JSON.stringify({ text: e.target.value }));
      e.target.value = '';
    }
  });
</script>
</body></html>''')

External links

Exercise

self-contained echo 서버 띄워. 브라우저에서 http://localhost:8000/ 열어. message 다섯 개 보내고 envelope 모양 로그에서 확인. 탭 닫아서 disconnect, 재연결 — 서버가 traceback 없이 깔끔하게 WebSocketDisconnect 로그하는지 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.