Socket

Anh-Thi Dinh
draft
  • Real life, a socket is
    • An entry point for a power cable.
      A software socket is also an entry point that accepts a network connection from another computer.
  • Sockets play a key role in keeping connections between computers neat and tidy.
  • Technologies make sockets possible: IP addresses, ports and TCP/IP (Transmission Control Protocol/Internet Protocol).
    • IP addresse: eg. 192.168.68.1 which is a unique number identifies your computer when its connected to a network using the Internet Protocol (IP).
      • When you type an website → you send also your IP addresse so that the server can send back the response to your computer.
    • Port: if you have only one IP address but with multiple services, how to connect to each of them? We use “ports”. For example, 192.168.68.1:3000.
      • We talk about “software port”, which is a specific number that identifies the specific app or service on your computer.
    • TCP (Transmission Control Protocol): When you send a large file over the internet, it doesn’t get sent in one big chunk. Instead, small packets are sent. This protocol ensures the connection is alive until the full file are sent.
      • TCP makes sure that all the packets arrive in their correct destination, and can then be re-ordered into the correct sequence.
      • TCP also sends an acknowledgment if the packet is successfully send. Otherwise, sender send it again.
  • Simple sense: socket = IP address + port → for sending / receiving information over the internet (two-way communication) + kept organized by TCP.
  • Socket.IO (How it works)
    • The bidirectional channel between server and client via WebSocket connection / HTTP long-polling.
    • 2 layers: the low-level plumbing (engine.io) and the high-level API (socket.io). Read more in the doc.
    • Namespaces: allows you to split the logic of your application over a single shared connection (also “multiplexing”)
    • Client side events: “connect”, “disconnect”, “reconnect”, … (eg. io.on(”connect”)) + other events.
    • Service side events: “connection”, “disconnect”, “disconnecting”
    • Some codes
      • 1// client
        2socket.emit("hello", "world", (response) => {
        3  console.log(response); // "got it"
        4});
        5
        6// server
        7io.on("connection", (socket) => {
        8  socket.on("hello", (arg, callback) => {
        9    console.log(arg); // "world"
        10    callback("got it");
        11  });
        12});
  • If you use NestJS, socket/websocket are supported out-of-the-box (you don’t need to install package socket.io)
Loading comments...