DEV Community

Cover image for Sockets Basics
Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Sockets Basics

šŸ“ 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?

  1. Simplifies Networking: Abstracts complex networking operations (like packet handling).
  2. Standardized Interface: Provides a universal API for network communication.
  3. Handles Addressing: Manages IPs and ports to ensure data reaches the correct process.
  4. Reliable Communication: Automatically handles retries, ordering, and error-checking for TCP.
  5. Supports Bi-directional Communication: Both ends can send and receive data.
  6. 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
    }
}
Enter fullscreen mode Exit fullscreen mode

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]))
}
Enter fullscreen mode Exit fullscreen mode

āœ… How It Works:

  1. Server

    • Listens on TCP port 12345.
    • Waits for client connections and reads incoming data.
    • Sends a response back to the client.
  2. Client

    • Connects to the server on TCP port 12345.
    • Sends a message to the server.
    • Receives the server's response.

This example demonstrates a basic but powerful use of TCP sockets in Go, showcasing how two programs can communicate over a network.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

šŸ‘‹ Kindness is contagious

Please leave a ā¤ļø or a friendly comment on this post if you found it helpful!

Okay