SocketIO



pip install flask-socketio<5.0.0 gevent eventlet gevent-websocket greenlet
npm i socket.io-client@2.3.1

import flask_socketio
import eventlet
eventlet.monkey_patch()
app = Flask(__name__)
socketio = SocketIO(app)

import openSocket from 'socket.io-client';
    

Scripts

main.py


from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#'
socketio = SocketIO(app)

@app.route('/')
def sessions():
    return render_template('session.html')

def messageReceived(methods=['GET', 'POST']):
    print('message was received!!!')

@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
    print('received my event: ' + str(json))
    socketio.emit('my response', json, callback=messageReceived)

if __name__ == '__main__':
    socketio.run(app, host='192.168.1.100',port=5001,debug=True)
    

templates/session.html


<!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Flask_Chat_App</title>
  </head>
  <body>

    <h3 style='color: #ccc;font-size: 30px;'>No message yet..</h3>
    <div class="message_holder"></div>

    <form action="" method="POST">
      <input type="text" class="username" placeholder="User Name"/>
      <input type="text" class="message" placeholder="Messages"/>
      <input type="submit"/>
    </form>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
    <script type="text/javascript">
      var socket = io.connect('http://' + document.domain + ':' + location.port);

      socket.on( 'connect', function() {
        socket.emit( 'my event', {
          data: 'User Connected'
        } )
        var form = $( 'form' ).on( 'submit', function( e ) {
          e.preventDefault()
          let user_name = $( 'input.username' ).val()
          let user_input = $( 'input.message' ).val()
          socket.emit( 'my event', {
            user_name : user_name,
            message : user_input
          } )
          $( 'input.message' ).val( '' ).focus()
        } )
      } )
      socket.on( 'my response', function( msg ) {
        console.log( msg )
        if( typeof msg.user_name !== 'undefined' ) {
          $( 'h3' ).remove()
          $( 'div.message_holder' ).append( '<div><b style="color: #000">'+msg.user_name+'</b> '+msg.message+'</div>' )
        }
      })
    </script>    
    

Then just run python main.py.

Demo

https://hidden-dusk-28735.herokuapp.com/session

References


  1. Asynchronous updates to a webpage with Flask and Socket.io
  2. Combining React with Socket.io for real-time goodness
  3. Real-time data update in chart.js using Socket.io | Angular Socket.io client
  4. Building your first Chat Application using Flask in 7 minutes
  5. Flask Docker container SocketIO Issues
  6. How do I send image to server via socket.io?