Sobes.tech
Junior — Middle

In what cases and for what purposes are sockets used in programming?

sobes.tech AI

Answer from AI

Sockets in programming are used to organize network interaction between processes, which can be on the same computer or different ones. In Go, sockets are used to create client-server applications, data exchange over TCP or UDP protocols.

Main use cases:

  • Implementation of network servers and clients (e.g., web server, chat, games).
  • Data exchange between distributed systems.
  • Creating custom protocols over TCP/UDP.

Example of creating a TCP server in Go:

package main

import (
    "fmt"
    "net"
)

func main() {
    ln, err := net.Listen("tcp", ":8080")
    if err != nil {
        panic(err)
    }
    defer ln.Close()

    for {
        conn, err := ln.Accept()
        if err != nil {
            fmt.Println("Connection error:", err)
            continue
        }
        go handleConnection(conn)
    }
}

func handleConnection(conn net.Conn) {
    defer conn.Close()
    buf := make([]byte, 1024)
    n, err := conn.Read(buf)
    if err != nil {
        fmt.Println("Read error:", err)
        return
    }
    fmt.Println("Received:", string(buf[:n]))
    conn.Write([]byte("Hello from the server!"))
}