Sling Academy
Home/Golang/Working with UDP and TCP Sockets in Go

Working with UDP and TCP Sockets in Go

Last updated: November 27, 2024

Introduction

Go, also known as Golang, is a modern programming language known for its simplicity, concurrency support, and efficiency. One of the areas where Go excels is in network programming, particularly with TCP and UDP sockets. This article will guide you through creating and using UDP and TCP sockets in Go, with simple examples to illustrate the concepts.

Understanding Sockets

Sockets are endpoints for sending and receiving data over networks. TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are the main protocols used in network communications:

  • TCP is connection-oriented, providing reliable, ordered, and error-checked delivery of a stream of bytes between applications.
  • UDP is connectionless, suitable for applications that need fast and efficient communication where occasional data loss is permissible.

UDP Socket in Go

Let's start with a simple UDP server and client in Go. UDP is simpler than TCP because it does not require connection management.

UDP Server

Here is how you create a basic UDP server in Go:


package main

import (
    "fmt"
    "net"
)

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

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

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

UDP Client

The following is an example of a simple UDP client:


package main

import (
    "fmt"
    "net"
)

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

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

    message := []byte("Hello, UDP Server!")
    _, err = conn.Write(message)
    if err != nil {
        fmt.Println("Error sending data:", err)
        return
    }
}

TCP Socket in Go

Now, let's look at how to set up a TCP server and client. TCP is more complex due to the need for connection management but offers reliable communication.

TCP Server

Bellow is a basic example of a TCP server in Go:


package main

import (
    "fmt"
    "net"
)

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

    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("Error accepting connection:", err)
            continue
        }
        go handleTCPConnection(conn)
    }
}

func handleTCPConnection(conn net.Conn) {
    defer conn.Close()
    buf := make([]byte, 1024)
    for {
        n, err := conn.Read(buf)
        if err != nil {
            fmt.Println("Error reading from connection:", err)
            return
        }
        fmt.Printf("Received %s\n", string(buf[:n]))
    }
}

TCP Client

Here's how you can create a simple TCP client in Go:


package main

import (
    "fmt"
    "net"
)

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

    message := "Hello, TCP Server!"
    _, err = conn.Write([]byte(message))
    if err != nil {
        fmt.Println("Error sending message:", err)
        return
    }
}

Conclusion

In this article, you have learned how to set up and use both UDP and TCP sockets in the Go language. While UDP is quicker and more efficient for lightweight tasks, TCP is essential when reliability and data integrity are your main goals. By understanding and utilizing both types of sockets, you can build robust networked applications that meet a wide array of needs.

Next Article: Creating Custom Protocols with Go's `net` Package

Previous Article: Using Go's `net` Package for Low-Level Networking

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant