Flask + Gevent + Sockets

Basically, I’ve been trying to set up a production environment for my flask and have been testing out things I’ve ended up with the following as the bare bones:
main.py

from gevent import monkey
monkey.patch_all()
from gevent.pywsgi import WSGIServer
from flask_compress import Compress
from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)

compress = Compress()

compress.init_app(app)

my_secret = os.environ['SECRET_KEY']
app.config['SECRET_KEY'] = my_secret

socketio = SocketIO(app, async_mode=async_mode)

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


if __name__ == '__main__':
    http_server = WSGIServer(('0.0.0.0', 8080), app)
    http_server.serve_forever()

index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js" integrity="sha512-pumBsjNRGGqkPzKHndZMaAG+bir374sORyzM3uulLV14lN5LyykqNk8eEeUlUkB3U0M4FApyaHraT65ihJhDpQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.6.1/socket.io.js" integrity="sha512-xbQU0+iHqhVt7VIXi6vBJKPh3IQBF5B84sSHdjKiSccyX/1ZI7Vnkt2/8y8uruj63/DVmCxfUNohPNruthTEQA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>
  <script type="text/javascript">
    $(document).ready(function() {
      var socket = io.connect("https://Language-Translator.akmalyahaya.repl.co")
      socket.on('connect', function() {
        socket.send("User connected: Main");
      });
  
      socket.on('message', function(data) {
        $('#messages').append($('<p>').text(data));
      });
    
    })
  </script>

  Hello world

  <div id="messages" class = "scroll">
    nice
  </div>
  
</body>

</html>

I had attempted to add a socket connection of some sort to transmit data between the 2 points but it doesn’t work (Note: This mainly just consisted of me adding random bits together without necessarily understanding/knowing what I’m even doing). Would be great if someone could point me in the right direction for the implementation of sockets or some other method of transmitting data between the 2 points.

1 Like

Try using http requests, as replit is not very supportive of non-http sockets. (Afaik, replit trys to transform, even non http sockets, to http)

1 Like

Do you have some sort of documentation/video that explains how I would do so?

Wait a second, looking at your code, I think you are trying to use web sockets. Not raw sockets. Those do work. Is this the code for https://language-translator.akmalyahaya.repl.co/ ? Also, async_mode should be undefined, and since you are not using async, remove that.

Got it working already with the following:

####################################################
####                  IMPORTS                   ####
####################################################

# Import Monkey module from gevent for monkey-patching
from gevent import monkey

# Monkey-patching standart Python library for async working
monkey.patch_all()

from flask import Flask, render_template
from flask_socketio import SocketIO, send
import pandas as pd
import os

#from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler

# Get the WSGI server
from gevent.pywsgi import WSGIServer

# Import Compress module from Flask-Compress for compress static content (HTML, CSS, JS)
from flask_compress import Compress

####################################################
####                  CONFIGS                   ####
####################################################

# Create the app
app = Flask('app')

# Create Compress with default params
compress = Compress()

# Init compress for our Flask app
compress.init_app(app)

codeTranslation = pd.read_csv("languageFiles/pseudocode.csv") 
# to get certain key from table --> print(codeTranslation["FLoop"].item())

my_secret = os.environ['SECRET_KEY']
app.config['SECRET_KEY'] = my_secret

socketio = SocketIO(app, cors_allowed_origins="*")



####################################################
####                   SERVER                   ####
####################################################

@socketio.on('message')
def handle_message(message):
  print(message, "MESSAGE")
  send("guh")


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




if __name__ == '__main__':
  # socketio.run(app, host="0.0.0.0", debug=True)
  socketio.run(app, host="0.0.0.0", port=9999, debug=True)
  
  # Create WSGI server with params for Repl.it (IP 0.0.0.0, port 8080) for our Flask app
  # To limit amount of sockets, add parameter called pool=pool and define before with pool = Pool(10000) 
  http_server = WSGIServer(('0.0.0.0', 9999), app, handler_class=WebSocketHandler)
  
  # Start WSGI server
  http_server.serve_forever()

I was looking back on my previous code and realised I had missed adding ‘cors_allowed_origins=“*”’ when creating the SocketIO which seemed to have fixed the issue (assuming I hadn’t accidentally removed bugged code and coincidentally fixed it) but thanks anyways

1 Like

Just as a follow up, whats the different between web sockets and raw sockets?

1 Like

Web sockets connect user to a website, sockets connect any computer to another computer. So, http requests rely on an underlying TCP socket.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.