How to create a WebSocket connection in Flask without port

0

I am completely new to Flask and Nginx, apart from this I am trying to use WebSocket and I need to do data transmission through a web page, but without having to specify the port, nor be running it in a virtual environment.

I have an Ubuntu server 16.04 with Flask and nginx. I followed this guide to configure it: link

No problem when I do data transmission while I am executing the instruction in the virtual environment:

(sattel-venv)shady@satel$ python sattel.py

And I see it in the address with port

http://107.170.30.166:5555/

The problem comes when I try to do this same thing, but already in the address without a written port:

http://107.170.30.166/

It does not transmit the data and I do not know why. The console reports the following message:

Firefox no pudo establecer una conexión con el servidor en ws://107.170.30.166:5555/recibe/.  conexion_socket.js:2:6
Error [object Event]  conexion_socket.js:13:8
1006  conexion_socket.js:8:3
Socket cerrado

These are my files.

On the server side:

sattel.py

from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def index():
    return render_template('trabajo_sockets/index.html')


@app.route('/recibe/')
def recibe():
    print("Recibiendo")
    primer_dato = True
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        while True:
            msg = ws.receive()
            if primer_dato and msg is not None:
                primer_dato = False
                # Lo que sea que se desee realizar con
                # el mensaje ...
                # Por ejemplo
                dato_recibido=msg
                print(dato_recibido)
                ws.send(dato_recibido)
                continue
            elif msg is not None:
                # Lo que sea que se desee realizar con
                # el mensaje ...
                # Por ejemplo
                dato_recibido=msg
                print(dato_recibido)
                ws.send(dato_recibido)
            else:
                break
    return "Hecho"


if __name__ == '__main__':
    http_server = WSGIServer(('107.170.30.166',5555), app, handler_class=WebSocketHandler)
    http_server.serve_forever()

On the client's side:

index.html

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script src="{{ url_for('static', filename='js/conexion_socket.js') }}"></script>
    <title>Implementando WebSockets</title>
</head>
<body>
    <div>
        Mensajero<br/><input type="text" name="envio" id="envio" value=""><br><button onclick="transmite()">Transmite</button>
    </div>
    <div>
        Receptor<br/><input type="text" name="recepcion" id="recepcion" value="">
    </div>
</body>
</html>

conexion_socket.js

function transmite(){
    ws = new WebSocket("ws://"+document.domain+":5555/recibe/");

    ws.onopen = function(evt) {
        ws.send($("#envio").val());
    }
    ws.onclose = function(respuesta){
        console.log(respuesta.code);
        console.log("Socket cerrado");
    }
    ws.onerror = function(err){
        ws.close();
        console.log("Error "+err);
    }
    ws.onmessage = function (msg) {
        console.log("Recibiendo");
        $("#recepcion").val(msg.data);
        ws.close();
    };
}

--- EDIT ---

These are the configuration files that I have:

sattel.ini (It is in the same directory as sattel.py)

[uwsgi]
module = wsgi:app

master = true
processes = 5

socket = sattel.sock
chmod-socket = 660
vacuum = true

die-on-term = true

/ etc / nginx / sites-available / sattel

server {
    listen 80;
    server_name 107.170.30.166;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/shady/sattel/sattel.sock;
    }
}

/etc/nginx/nginx.conf

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

}


#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
# 
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

/etc/systemd/system/sattel.service

[Unit]
Description=Instancia uWSGI configurada para implementar Sockets
After=network.target

[Service]
User=shady
Group=www-data
WorkingDirectory=/home/shady/sattel
Environment="PATH=/home/shady/sattel/sattel-venv/bin"
ExecStart=/home/shady/sattel/sattel-venv/bin/uwsgi --ini sattel.ini

[Install]
WantedBy=multi-user.target

---- END EDIT ----

As a note, I also tried removing the port of the address in the conexion_socket.js file, it reflects a message very similar to the previous one:

Firefox no pudo establecer una conexión con el servidor en ws://107.170.30.166/recibe/.  conexion_socket.js:2:6
Error [object Event]  conexion_socket.js:13:8
1006  conexion_socket.js:8:3
Socket cerrado

Thank you very much for your attention and I will greatly appreciate your help.

    
asked by Abraham Baez 12.05.2017 в 06:41
source

0 answers