š Notes on Sockets and Their Importance
What is a Socket?
- A socket is a software abstraction that enables communication between devices over a network.
- It's identified by an IP address and a port number.
- Sockets allow programs to send and receive data.
Why Do We Need Sockets?
- Simplifies Networking: Abstracts complex networking operations (like packet handling).
- Standardized Interface: Provides a universal API for network communication.
- Handles Addressing: Manages IPs and ports to ensure data reaches the correct process.
- Reliable Communication: Automatically handles retries, ordering, and error-checking for TCP.
- Supports Bi-directional Communication: Both ends can send and receive data.
- Protocol Flexibility: Works with TCP for reliable communication and UDP for faster, connectionless communication.
Types of Sockets:
- TCP Socket: Reliable, connection-based communication (e.g., gRPC, HTTP).
- UDP Socket: Unreliable, fast, connectionless communication (e.g., DNS, video streaming).
āļø Basic TCP Socket Programming in Golang
Server Code (TCP)
package main
import (
"fmt"
"net"
)
func main() {
// Start listening on port 12345
listener, err := net.Listen("tcp", ":12345")
if err != nil {
fmt.Println("Error starting server:", err)
return
}
defer listener.Close()
fmt.Println("Server is listening on port 12345...")
// Accept incoming connections
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
return
}
defer conn.Close()
fmt.Println("Connected to client")
// Read data from client
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
fmt.Println("Error reading from client:", err)
return
}
fmt.Printf("Received from client: %s\n", string(buffer[:n]))
// Send response to client
_, err = conn.Write([]byte("Hello from server!"))
if err != nil {
fmt.Println("Error writing to client:", err)
return
}
}
Client Code (TCP)
package main
import (
"fmt"
"net"
)
func main() {
// Connect to the server
conn, err := net.Dial("tcp", "localhost:12345")
if err != nil {
fmt.Println("Error connecting to server:", err)
return
}
defer conn.Close()
// Send message to the server
_, err = conn.Write([]byte("Hello from client!"))
if err != nil {
fmt.Println("Error sending message:", err)
return
}
// Receive response from server
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
fmt.Println("Error reading from server:", err)
return
}
fmt.Printf("Received from server: %s\n", string(buffer[:n]))
}
ā How It Works:
-
Server
- Listens on TCP port
12345
. - Waits for client connections and reads incoming data.
- Sends a response back to the client.
- Listens on TCP port
-
Client
- Connects to the server on TCP port
12345
. - Sends a message to the server.
- Receives the server's response.
- Connects to the server on TCP port
This example demonstrates a basic but powerful use of TCP sockets in Go, showcasing how two programs can communicate over a network.
Top comments (0)