Sobes.tech
Senior

How does WebSocket connection work in architecture — when is it established and who communicates with whom?

sobes.tech AI

Answer from AI

WebSocket connection is established through a special handshake over the HTTP protocol:

  1. The client sends an HTTP request with the header Upgrade: websocket to switch to the WebSocket protocol.
  2. The server supporting WebSocket responds with a confirmation and switches to a bidirectional connection.

After the connection is established:

  • The client and server maintain a persistent TCP connection.
  • Both parties can send messages at any time without needing to re-establish the connection.

In architecture, this allows for real-time communication, such as chat or real-time data updates.

Example in Go using the gorilla/websocket package:

var upgrader = websocket.Upgrader{}

func wsHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Print("upgrade error:", err)
        return
    }
    defer conn.Close()

    for {
        _, msg, err := conn.ReadMessage()
        if err != nil {
            break
        }
        // Message processing
        conn.WriteMessage(websocket.TextMessage, msg) // echo
    }
}

Thus, WebSocket provides a bidirectional, persistent connection between the client and server.