Senior
What are sockets and what types are there?.
sobes.tech AI
Answer from AI
Sockets are a programming interface for organizing network interaction between processes, often between different computers. They allow applications to exchange data over a network using various protocols.
Main types of sockets:
- Stream sockets (TCP) — provide reliable, connection-oriented data transfer. Used for the TCP protocol.
- Datagram sockets (UDP) — provide message transfer without establishing a connection, without delivery guarantees. Used for the UDP protocol.
- Raw sockets — allow working with network protocols at a low level, for example, to implement custom protocols or analyze traffic.
In Go, the net package is used for working with sockets. Example of creating a TCP server:
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("Error accepting connection:", err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(c net.Conn) {
defer c.Close()
buf := make([]byte, 512)
n, err := c.Read(buf)
if err != nil {
fmt.Println("Error reading:", err)
return
}
fmt.Println("Received:", string(buf[:n]))
}
Thus, sockets are a fundamental mechanism for network interaction, and their types determine the method and reliability of data transfer.