简体   繁体   中英

Trouble deploying a Flask Websockets App on Heroku

I've written a Flask app that uses websockets, and it's running fine for me locally .

But when I try to deploy it via Heroku and open it in the browser, I get these errors:

In Chrome: WebSocket connection to 'wss://flask-realtime-chat-app.herokuapp.com/chat' failed: Error during WebSocket handshake: Unexpected response code: 404 .

In Firefox: Firefox can't establish a connection to the server at ws://flask-realtime-chat-app.herokuapp.com/chat.

Here are the relevant parts of my code:

import json
from flask import Flask, send_from_directory, request
from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)

@app.route("/")
def index():
    return send_static("index.html")

@app.route("/static/<path>")
def send_static(path):
    return send_from_directory("../client/static", path)

connections = []
messages = []
usernames = {}

@sockets.route("/chat")
def chat_socket(web_socket):
    global connections, usernames
    connections = add_socket(web_socket, connections)

    while not web_socket.closed:
        data = json.loads(web_socket.receive())
        connections = remove_closed_sockets(connections)
        messages.append(data)
        json_message = json.dumps(data)
        send_message(json_message, connections)

def add_socket(web_socket, connections):
    return connections + [web_socket]

def remove_closed_sockets(connections):
    return [c for c in connections if not c.closed]

def send_message(message, connections):
    for socket in connections:
        socket.send(message)

if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()

Front end:

if (window.location.protocol == "https:") {
  var ws_scheme = "wss://";
} else {
  var ws_scheme = "ws://";
}

var socket = new WebSocket(ws_scheme + location.host + "/chat");

socket.onopen = function (event) {
    console.log("Websocket open!");
}

socket.onclose = function (event) {
    console.log("Websocket closed!");
}

socket.onmessage = function (event) {
    var incomingMessage = JSON.parse(event.data);

    if (incomingMessage["message"]) {
        addMessageToChatScreen(incomingMessage);
    } else if (incomingMessage["usernames"]) {
        usernames = incomingMessage["usernames"];
    }
}

...

function sendMessage() {
    var data = JSON.stringify({
        uid: uid,
        message: $("#message_input").val()
    });

    socket.send(data);
    $("#message_input").val("");
}

Any advice would be greatly appreciated!

Provide a worker class in procfile. Here I used eventlet.

web: gunicorn --worker-class eventlet -w 1 --pythonpath app:app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM