Flask-SocketIO 서버 설치 및 코드 사용 예

10894 단어 FlaskSocketIO서버
Flask-Sockets를 쉽게 설치할 수 있습니다.
pip install flask-socketio
Flask-SocketIO는gevent 라이브러리에 의존합니다. 현재는python2에서만 실행할 수 있습니다.gevent도 곧python3에 지원할 것입니다.
다음은 Flask-SocketIO가 Flask 응용 프로그램에서 구현한 예입니다.

from flask import Flask, request, jsonify,render_template
from flask_socketio import SocketIO, emit


app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)


@app.route('/')
def index():
  return render_template('test.html')

# my event: 
@socketio.on('my_event', namespace='/chat')
def test_message(message):
  print(message)
  emit('my_response', {'data': message['data']})


# my broadcast event:: ( )
@socketio.on('my_broadcast event', namespace='/chat')
def test_message(message):
  print(message)
  emit('my_response', {'data': message['data']}, broadcast=True)

##################################################################
# 
@socketio.on('connect', namespace='/chat')
def test_connect():
  print(" ")
  emit('my_response', {'data': 'Connected'})

@socketio.on('disconnect', namespace='/chat')
def test_disconnect():
  print(" ")
  print('Client disconnected')

if __name__ == '__main__':
  socketio.run(app,host='0.0.0.0',port=8200,debug=True)
대응하는 테스트.html, 질문 주의:flask는 시작 파일과 동급의templates에서 템플릿을 찾습니다.
test.html
정부의 완전한 예시

#!/usr/bin/env python
from threading import Lock
from flask import Flask, render_template, session, request, \
  copy_current_request_context
from flask_socketio import SocketIO, emit, join_room, leave_room, \
  close_room, rooms, disconnect

# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on installed packages.
async_mode = None

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()

def background_thread():
  """Example of how to send server generated events to clients."""
  count = 0
  while True:
    socketio.sleep(100)
    count += 1
    socketio.emit('my_response',
           {'data': 'Server generated event', 'count': count},
           namespace='/test')

@app.route('/')
def index():
  return render_template('test1.html', async_mode=socketio.async_mode)

@socketio.on('my_event', namespace='/test')
def mtest_message(message):
  print(message)
  session['receive_count'] = session.get('receive_count', 0) + 1
  # print(message)
  # print(message['data'])
  emit('my_response',
     {'data': message['data'], 'count': session['receive_count']})

@socketio.on('my_broadcast_event', namespace='/test')
def mtest_broadcast_message(message):
  print(message)
  session['receive_count'] = session.get('receive_count', 0) + 1
  emit('my_response',
     {'data': message['data'], 'count': session['receive_count']},
     broadcast=True)

@socketio.on('join', namespace='/test')
def join(message):
  print(message)
  join_room(message['room'])
  session['receive_count'] = session.get('receive_count', 0) + 1
  emit('my_response',
     {'data': 'In rooms: ' + ', '.join(rooms()),
     'count': session['receive_count']})

@socketio.on('leave', namespace='/test')
def leave(message):
  print(message)
  leave_room(message['room'])
  session['receive_count'] = session.get('receive_count', 0) + 1
  emit('my_response',
     {'data': 'In rooms: ' + ', '.join(rooms()),
     'count': session['receive_count']})

@socketio.on('close_room', namespace='/test')
def close(message):
  session['receive_count'] = session.get('receive_count', 0) + 1
  emit('my_response', {'data': 'Room ' + message['room'] + ' is closing.',
             'count': session['receive_count']},
     room=message['room'])
  close_room(message['room'])

@socketio.on('my_room_event', namespace='/test')
def send_room_message(message):
  session['receive_count'] = session.get('receive_count', 0) + 1
  emit('my_response',
     {'data': message['data'], 'count': session['receive_count']},
     room=message['room'])


##################################################################
# 
@socketio.on('connect', namespace='/test')
def test_connect():
  print(" ")
  emit('my response', {'data': 'Connected'})

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
  print(" ")
  print('Client disconnected')


if __name__ == '__main__':
  socketio.run(app, debug=True,port= 8200)
test1.html

<!DOCTYPE HTML>
<html>
<head>
  <title>Flask-SocketIO Test</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
  <script type="text/javascript" charset="utf-8">
      $(document).ready(function(){
     var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
       socket.on('my_response', function(msg) {
         $('#log').append('<p>Received: ' + msg.data + '</p>');
    });

      $('form#emit').submit(function(event) {
        socket.emit('my_event', {data: $('#emit_data').val()});
        return false;
      });
      $('form#broadcast').submit(function(event) {
        socket.emit('my_broadcast_event', {data: $('#broadcast_data').val()});
        return false;
      });
      $('form#join').submit(function(event) {
        socket.emit('join', {room: $('#join_room').val()});
        return false;
      });
      $('form#leave').submit(function(event) {
        socket.emit('leave', {room: $('#leave_room').val()});
        return false;
      });
      $('form#send_room').submit(function(event) {
        socket.emit('my_room_event', {room: $('#room_name').val(), data: $('#room_data').val()});
        return false;
      });
      $('form#close').submit(function(event) {
        socket.emit('close_room', {room: $('#close_room').val()});
        return false;
      });
      $('form#disconnect').submit(function(event) {
        socket.emit('disconnect_request');
        return false;
      });
    });
  </script>
</head>
<body>
  <h1>Flask-SocketIO Test</h1>
  <p>Async mode is: <b>{{ async_mode }}</b></p>
  <p>Average ping/pong latency: <b><span id="ping-pong"></span>ms</b></p>
  <h2>Send:</h2>
  <form id="emit" method="POST" action='#'>
    <input type="text" name="emit_data" id="emit_data" placeholder="Message">
    <input type="submit" value="Echo">
  </form>
  <form id="broadcast" method="POST" action='#'>
    <input type="text" name="broadcast_data" id="broadcast_data" placeholder="Message">
    <input type="submit" value="Broadcast">
  </form>
  <form id="join" method="POST" action='#'>
    <input type="text" name="join_room" id="join_room" placeholder="Room Name">
    <input type="submit" value="Join Room">
  </form>
  <form id="leave" method="POST" action='#'>
    <input type="text" name="leave_room" id="leave_room" placeholder="Room Name">
    <input type="submit" value="Leave Room">
  </form>
  <form id="send_room" method="POST" action='#'>
    <input type="text" name="room_name" id="room_name" placeholder="Room Name">
    <input type="text" name="room_data" id="room_data" placeholder="Message">
    <input type="submit" value="Send to Room">
  </form>
  <form id="close" method="POST" action="#">
    <input type="text" name="close_room" id="close_room" placeholder="Room Name">
    <input type="submit" value="Close Room">
  </form>
  <form id="disconnect" method="POST" action="#">
    <input type="submit" value="Disconnect">
  </form>
  <h2>Receive:</h2>
  <div id="log"></div>
</body>
</html>
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기