Tamir Polyakov
Tamir Polyakov

Reputation: 164

How does connect and disconnect work with Sockets

I began learning sockets today and I have some questions about how it works. I'm using flask_socketIO and this is the code I found in a tutorial

Main.py

from flask import Flask
from flask_socketio import SocketIO, send

app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"
socketio = SocketIO(app, cors_allowed_origins="*")

@socketio.on("message")
def handleMessage(msg):
    print("Message: " + msg)
    send(msg, broadcast=True)

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

Index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Chat room</title>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
      integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.0/socket.io.js"
      integrity="sha512-/xb5+PNOA079FJkngKI2jvID5lyiqdHXaUUcfmzE0X0BdpkgzIWHC59LOG90a2jDcOyRsd1luOr24UCCAG8NNw=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>
  </head>
  <body>
    <script type="text/javascript">
      $(document).ready(() => {
        var socket = io.connect("http://127.0.0.1:5000");
        socket.on("connect", () => {
          socket.send("User has connected!");
        });
        socket.once("disconnect", () => {
          socket.send("User has disconnected!");
          console.log("User Disconnected");
        });
        socket.on("message", (msg) => {
          $("#messages").append("<li>" + msg + "</li>");
          console.log("Message recieved");
        });
        $("#sendButton").on("click", () => {
          socket.send($("#myMessage").val());
          $("#myMessage").val("");
        });
      });
    </script>
    <ul id="messages"></ul>
    <input type="text" id="myMessage" />
    <button id="sendButton">Send</button>
  </body>
</html>

I understand how message works but I don't understand how the connect and disconnect events work. When a new user goes on the page, it logs out both in terminal and on website"User has connected". Why does it do that even though I don't have print() for my terminal or a function similar to

        $("#sendButton").on("click", () => {
          socket.send($("#myMessage").val());
          $("#myMessage").val("");
        });

for the website. Also disconnect doesn't work at all, it doesn't console.log when a user disconnects. Does anyone know why?

Upvotes: 1

Views: 386

Answers (1)

When a new user goes on the page, it logs out both in terminal and on website"User has connected". Why does it do that even though I don't have print() for my terminal or a function similar to

The browser sends it to the the server. The server prints it (in the server's terminal) and also sends it to all the connected browsers, which log it in #messages.

Also disconnect doesn't work at all, it doesn't console.log when a user disconnects. Does anyone know why?

After the browser disconnects the browser tries to send the message to the server. The server never gets it because the browser already disconnected. Possibly the browser throws an exception when you try to send to a disconnected socket and so it never gets to the next line of code which calls console.log.

Upvotes: 2

Related Questions