0

I have Flask server, which handles HTTP requests but also WebSocket using flask-socketio. Code of server here:

from flask_socketio import SocketIO, emit
from flask import Flask

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on('response')
def message(data):  
    time.sleep(1)
    emit('sensor', {"data": "hello"})
    
@socketio.on('connect')
def connect():
    emit('after connect')

if __name__ == '__main__':
    socketio.run(app)

and script tag in html looks like this:

<script>
    var socket = io("ws://192.168.100.3:5000");
            
    socket.on('after connect', function(msg) {
        console.log('connected')
        socket.emit('response', msg)
    });
            
    socket.on('sensor', function(msg) {
        console.log(msg.data)
        socket.emit('response', msg)
    });     
</script>

Everything works, I got the communication, but one thing that concerning me is that in terminal where server run I get code 200 for GET and POST requests.

192.168.100.10 - - [17/Apr/2022 11:36:27] "GET /socket.io/?EIO=2&transport=polling&t=1650191787548-1094&sid=faed6806df0a437d8d17bd8a294f8754 HTTP/1.1" 200 -
192.168.100.10 - - [17/Apr/2022 11:36:27] "POST /socket.io/?EIO=2&transport=polling&t=1650191788570-1095&sid=faed6806df0a437d8d17bd8a294f8754 HTTP/1.1" 200 -

I get response in console I think communication is right. But with those request that I am "making" every second resources usage in web browser is getting bigger. Small amount but still. As far as I know WebSockets should not send HTTP requests to server, but it has to be TCP/IP constant connection.

What am I doing wrong, or it is my WebSockets understanding wrong?

2
  • better create minimal working code which we can copy and run. And add details about browser, python, SocketIO module - and put it in question, not in comments. Sometimes when it can't connect directly by socket then it can use standard HTTP for connection. Commented Apr 17, 2022 at 12:40
  • This is not question that resemble exact error in a code, rather question on how thing works. I do not see a reason to put here my .html as it is simple. My question is simple and I need explanation of theory behind not such a obvious solution. Commented Apr 17, 2022 at 17:11

1 Answer 1

2

The GET and POST requests are there because you are using Socket.IO. As stated in its documentation, Socket.IO starts with HTTP long-polling before it attempts to establish a WebSocket connection. It will also fallback to HTTP long-polling if it cannot use WebSocket.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.