Back

Talking Through Pipes: TCP/IP Connections in Golang

Apr 24 2024
10min
🕐 Current time : 29 Mar 2025, 05:04 AM
The full Astro logo.

The internet, that vast and ever-expanding network of information, relies on a complex language for devices to communicate. TCP/IP (Transmission Control Protocol/Internet Protocol) acts as the foundation of this language, ensuring reliable and ordered data exchange between machines. Golang, a powerful programming language, provides intuitive tools to leverage TCP/IP connections for building network applications.

This article, designed for a 10-minute read, dives into the world of TCP/IP connections in Golang. We’ll explore the fundamentals, create basic client and server examples, and delve into some essential aspects of data exchange.

Understanding TCP/IP Connections

Imagine two people having a conversation. They take turns speaking, ensuring messages are received clearly and in the correct order. TCP/IP connections function similarly. It’s a connection-oriented protocol, meaning a dedicated link is established between two devices before data exchange begins. This ensures reliable, sequenced delivery of information.

Golang’s TCP/IP Toolkit: The net Package

Golang provides the net package, a treasure trove for network programming. This package offers functions and structures to establish TCP/IP connections, send and receive data, and manage communication flow.

Building a Simple TCP Server in Golang

Let’s create a basic TCP server that listens for incoming connections and responds with a greeting message. Here’s a breakdown of the code:

package main

import (
    "fmt"
    "net"
)

func handleConnection(conn net.Conn) {
    defer conn.Close()
    fmt.Fprintf(conn, "Hello, world!\n")
}

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

    fmt.Println("Listening on port 8080...")
    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println(err)
            continue
        }
        go handleConnection(conn)
    }
}

Code explanation:

  1. We import the net and fmt packages.

  2. The handleConnection function takes a net.Conn object as input, representing the established connection.

  3. Inside handleConnection, we use fmt.Fprintf to write the greeting message to the connection and then close it using defer.

  4. In the main function, we use net.Listen to create a listener object on port 8080.

  5. We enter an infinite loop using for to continuously accept incoming connections using listener.Accept.

  6. For each accepted connection, a new goroutine (lightweight thread) is spawned using go to handle the communication with the client in the handleConnection function. This allows the server to handle multiple clients concurrently.

Creating a TCP Client

Now, let’s build a simple TCP client that connects to the server and receives the greeting message.

package main

import (
    "fmt"
    "net"
)

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

    buf := make([]byte, 1024)
    n, err := conn.Read(buf)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(string(buf[:n]))
}

Above code explanation:

  1. We import the net and fmt packages.

  2. We use net.Dial to establish a connection to the server running on localhost port 8080.

  3. A buffer (buf) is created to store the incoming data.

  4. We use conn.Read to read data from the connection into the buffer.

  5. Finally, we print the received message as a string.

Sending and Receiving Data: Beyond Basic Greetings

While our examples showcase basic communication, Golang offers more for data exchange. You can use methods like conn.Write to send data from the client or server and conn.Read to receive data in a loop for continuous communication.

Remember to Close Connections!

Always ensure proper resource management by closing connections using conn.Close when communication is complete. This frees up resources for other connections. 💡

Read more in this Series:

Find me on

GitHub LinkedIn LinkedIn X Twitter
© 2022 to 2025 : Amit Prakash