I am trying to foward localhost:4000 -> localhost:8000 i am using nginx its working fine for static pages but when i try to use websockets it doesnt work
here is the code im using:
server.py:
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app, namespace='/counter')
def counter_thread():
count = 0
while count <= 100:
socketio.emit('counter_update', {'count': count}, namespace='/counter')
count += 1
socketio.sleep(1)
@app.route('/')
def index():
return "Hello, World!"
@app.route('/time1')
def time1():
return render_template('counter.html')
@socketio.on('connect', namespace='/counter')
def counter_connect():
global count_thread
if 'count_thread' not in globals():
count_thread = socketio.start_background_task(target=counter_thread)
if __name__ == '__main__':
socketio.run(app, port=4000)
counter.html:
<!DOCTYPE html>
<html>
<head>
<title>Real-time Counter</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.1/socket.io.js"></script>
</head>
<body>
<h1>Real-time Counter</h1>
<div id="counter"></div>
<script>
var socket = io.connect("http://"+ document.domain + ':' + location.port + '/counter');
socket.on('counter_update', function(data) {
document.getElementById('counter').innerHTML = 'Counter: ' + data.count;
});
</script>
</body>
</html>
my nginx conf is:
events {
worker_connections 1024;
}
http {
server {
listen 8000;
server_name localhost;
location / {
proxy_pass http://127.0.0.1:4000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
}
access.log(small sample):
127.0.0.1 - - [22/Mar/2024:01:46:27 +0200] "GET /socket.io/?EIO=4&transport=websocket&sid=0W0s74jOOVnn1CoIAAAE HTTP/1.1" 400 36 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
127.0.0.1 - - [22/Mar/2024:01:46:27 +0200] "POST /socket.io/?EIO=4&transport=polling&t=OvZQAl-&sid=0W0s74jOOVnn1CoIAAAE HTTP/1.1" 400 36 "http://127.0.0.1:8000/time1" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
127.0.0.1 - - [22/Mar/2024:01:46:28 +0200] "POST /socket.io/?EIO=4&transport=polling&t=OvZQAmX&sid=0W0s74jOOVnn1CoIAAAE HTTP/1.1" 400 36 "http://127.0.0.1:8000/time1" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
static stuff is fine but the sockets arent working:
port8000forwardof4000(not working)
now im not sure if this is a problem with my setup for sockets or if this is a problem with my nginx.conf