사용 환경 : mac
웹 브라우저와 웹 서버 간의 실시간 양방향 통신을 가능하게 하는 JavaScript 라이브러리
실시간 응용 프로그램을 구축 할 때 사용
클라이언트가 주기적인 요청을 할 필요 없이 즉시 데이터를 송수신 가능
WebSockets
Socket.IO는 효율적인 대기 시간이 짧은 전이중 통신을 위해 브라우저에서 사용 가능한 경우 WebSocket을 사용
이벤트 기반 통신
클라이언트와 서버는 이벤트를 내보내고 수신할 수 있으므로 사용자 지정 작업 및 데이터 교환을 쉽게 구현
브로드캐스팅
Socket.IO는 여러 클라이언트 또는 특정 룸이나 네임스페이스에 연결된 모든 클라이언트에 메시지를 브로드캐스트
교차 플랫폼 호환성
Socket.IO는 웹 브라우저, 모바일 장치 및 서버를 포함한 다양한 플랫폼에서 작동하므로 다중 장치 지원을 통해 실시간 응용 프로그램을 구축하는 데 적합
websocket_test.py
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")
@app.route('/')
def index():
return render_template('index_websocket.html')
@socketio.on('message')
def handle_message(message):
print('Received message:', message)
socketio.send('Server received: ' + message)
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000)
templates/index_websocket.html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Example</title>
</head>
<body>
<h1>WebSocket Example</h1>
<input type="text" id="message" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<div id="output"></div>
<script src="<https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.2/socket.io.js>"></script>
<script type="text/javascript">
const socket=io.connect('<http://localhost:5000>');
socket.on('message',function(message){
document.getElementById('output').innerHTML+='<p>'+message+'</p>';
});
function sendMessage() {
const input=document.getElementById('message');
const message=input.value;
input.value='';
socket.send(message);
// 화면에 표시
document.getElementById('output').innerHTML += '<p>You: ' + message + '</p>';
}
</script>
</body>
</html>