Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Creating a TCP Server in Go

Introduction

In this tutorial, we will learn how to create a TCP server in Go. TCP (Transmission Control Protocol) is a standard that defines how to establish and maintain a network conversation through which application programs can exchange data. A TCP server listens for incoming connections and handles them appropriately.

Setting Up Your Environment

Before we start coding, ensure you have Go installed on your machine. You can download and install Go from the official website: https://golang.org/dl/.

To verify the installation, run the following command in your terminal:

go version

You should see output similar to:

go version go1.17.1 linux/amd64

Creating the TCP Server

Let's start by creating a simple TCP server. First, create a new directory for your project and navigate into it:

mkdir tcp-server
cd tcp-server

Create a new file named server.go and open it in your favorite text editor. Add the following code:

package main

import (
    "fmt"
    "net"
)

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

    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("Error:", err.Error())
            return
        }
        go handleRequest(conn)
    }
}

func handleRequest(conn net.Conn) {
    buffer := make([]byte, 1024)
    for {
        n, err := conn.Read(buffer)
        if err != nil {
            fmt.Println("Error:", err.Error())
            return
        }
        fmt.Println("Received:", string(buffer[:n]))
        conn.Write(buffer[:n])
    }
}

In this code:

  • We use net.Listen to create a TCP listener on port 8080.
  • The defer statement ensures that the listener is closed when the function exits.
  • We use an infinite loop to accept incoming connections.
  • Each connection is handled in a separate goroutine using the handleRequest function.
  • The handleRequest function reads data from the connection and echoes it back to the client.

Running the TCP Server

To run the TCP server, use the following command in your terminal:

go run server.go

You should see output indicating that the server is listening on port 8080:

Server is listening on port 8080

Testing the TCP Server

To test the TCP server, you can use a telnet client or a simple netcat command. Open a new terminal window and run the following command:

telnet localhost 8080

Alternatively, you can use netcat:

nc localhost 8080

Once connected, type a message and press Enter. You should see the server echo the message back to you:

Hello, server!
Hello, server!

Conclusion

In this tutorial, we learned how to create a simple TCP server in Go. We covered setting up the environment, writing the server code, running the server, and testing it using telnet or netcat. This basic implementation can be extended to handle more complex scenarios, such as handling multiple clients, processing different types of requests, and more.

Happy coding!