TCP and UDP Sockets in Go

Networking with TCP and UDP sockets forms the backbone of communication between different devices over a network. In this chapter, we'll explore TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) sockets in Go, covering everything from basic socket programming to advanced techniques.

TCP and UDP are two of the most commonly used transport layer protocols in computer networks. TCP provides reliable, connection-oriented communication, while UDP offers lightweight, connectionless communication.

Basic Socket Programming

Socket programming involves creating endpoints for communication between two processes over a network. In Go, the net package provides support for working with sockets.

TCP Socket Programming

TCP sockets provide reliable, stream-oriented communication between clients and servers.

				
					package main

import (
    "fmt"
    "net"
)

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

    fmt.Println("TCP server listening on port 8080")

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

func handleConnection(conn net.Conn) {
    defer conn.Close()
    // Handle client connection
}

				
			
  • We create a TCP server that listens on port 8080 using net.Listen().
  • We accept incoming connections using ln.Accept() in a loop.
  • For each connection, we spawn a new goroutine to handle it concurrently.

UDP Socket Programming

UDP sockets provide connectionless, unreliable communication between clients and servers.

				
					package main

import (
    "fmt"
    "net"
)

func main() {
    addr, err := net.ResolveUDPAddr("udp", ":8080")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    conn, err := net.ListenUDP("udp", addr)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer conn.Close()

    fmt.Println("UDP server listening on port 8080")

    for {
        buffer := make([]byte, 1024)
        n, addr, err := conn.ReadFromUDP(buffer)
        if err != nil {
            fmt.Println("Error:", err)
            continue
        }
        fmt.Printf("Received UDP message from %s: %s\n", addr, string(buffer[:n]))
    }
}

				
			
  • We resolve the UDP address using net.ResolveUDPAddr() and listen on port 8080 using net.ListenUDP().
  • We read incoming UDP messages using conn.ReadFromUDP() in a loop and print them to the console.

Advanced Socket Programming Techniques

In this section, we’ll explore advanced socket programming techniques for TCP and UDP sockets in Go

Concurrent TCP Server

Concurrent TCP servers use goroutines to handle multiple client connections concurrently.

				
					package main

import (
    "fmt"
    "net"
)

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

    fmt.Println("Concurrent TCP server listening on port 8080")

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

func handleConnection(conn net.Conn) {
    defer conn.Close()
    // Handle client connection concurrently
}

				
			

Similar to the basic TCP server example, but we handle each client connection in a separate goroutine.

UDP Client

UDP clients send datagrams to UDP servers without establishing a connection.

				
					package main

import (
    "fmt"
    "net"
)

func main() {
    addr, err := net.ResolveUDPAddr("udp", "localhost:8080")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    conn, err := net.DialUDP("udp", nil, addr)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer conn.Close()

    message := []byte("Hello, UDP server!")
    _, err = conn.Write(message)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Message sent to UDP server")
}

				
			
  • We resolve the UDP address and dial the UDP server using net.ResolveUDPAddr() and net.DialUDP().
  • We send a message to the server using conn.Write().

TCP and UDP sockets are essential for building networked applications in Go. By understanding the basic principles of socket programming and exploring advanced techniques, you can develop robust and scalable networked applications for various use cases. Experiment with different socket programming patterns, explore error handling strategies, and optimize performance to become proficient in TCP and UDP socket programming with Go. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India