๐ŸŒ

flask websocket

Tags
Python
ID matched
Created
Mar 16, 2023 02:24 PM
Last Updated
Last updated July 15, 2023
ย 
ย 
ย 

1. ์„œ๋ฒ„

  • ํŒจํ‚ค์ง€ ์„ค์น˜๋Š” ์•„๋ž˜์˜ ๋ช…๋ น์–ด๋กœ ํ•œ๋‹ค.
    • pip3 install Flask-SocketIO==5.1.2 python-engineio==4.3.2 python-socketio==5.6.0 eventlet
  • ์„œ๋ฒ„ ์ฝ”๋“œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ž‘์„ฑํ•œ๋‹ค.
    • from flask import Flask from flask_socketio import SocketIO import datetime import eventlet app = Flask(__name__) socketio = SocketIO(app) socketio.init_app(app, cors_allowed_origins="*") @app.route('/') def hello(): return '<h1>This is site</h1>' def send_count_in_intervals(): count = 0 while True: socketio.sleep(1) socketio.emit('message', { 'time': datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), 'count': count }) count += 1 if __name__ == '__main__': thread = socketio.start_background_task(send_count_in_intervals) eventlet.wsgi.server(eventlet.listen(('', 9999)), app)
  • ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•˜๋ฉด, ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋กœ๊ทธ๋ฅผ ๊ธฐ๋กํ•œ๋‹ค.
    • notion image
ย 
ย 

2. ํด๋ผ์ด์–ธํŠธ

  • ํŒจํ‚ค์ง€ ์„ค์น˜๋Š” ์•„๋ž˜์˜ ๋ช…๋ น์–ด๋กœ ํ•œ๋‹ค.
    • pip3 install python-socketio
  • ํด๋ผ์ด์–ธํŠธ ์ฝ”๋“œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ž‘์„ฑํ•œ๋‹ค.
    • import socketio sio = socketio.Client() sio.connect('ws://127.0.0.1:9999') @sio.on('message') def receive_message(message): print('message', message)
  • ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•˜๋ฉด, ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋กœ๊ทธ๋ฅผ ๊ธฐ๋กํ•œ๋‹ค.
    • notion image
ย 
ย 

3. ํฌ์ŠคํŠธ๋งจ ํ…Œ์ŠคํŠธ

  • WebSocket Request๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.
    • notion image
  • Raw โ†’ Socket.IO๋กœ ๋ณ€๊ฒฝํ•œ๋‹ค.
    • notion image
  • ์ ‘์† ์ฃผ์†Œ๋Š” ws ํ˜น์€ wss ํ”„๋กœํ† ์ฝœ๋กœ ์ ์ ˆํ•œ ์ฃผ์†Œ๋ฅผ ์ž…๋ ฅํ•œ๋‹ค.
    • notion image
  • Events์— ์ ์ ˆํ•œ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜๊ณ , Listen on connect๋ฅผ ํ™œ์„ฑํ™”ํ•œ๋‹ค.
    • notion image
  • ์„ค์ •์ด ์™„๋ฃŒ๋œ ํ›„, ์—ฐ๊ฒฐ์„ ํ•ด์„œ ์ ‘์†์„ ํ…Œ์ŠคํŠธํ•ด๋ณธ๋‹ค.
    • notion image
ย 
ย