Go by Example

TCP Server

Accept TCP connections, handle clients concurrently, and set deadlines to bound stalled reads.

TCP is a set of rules for sending a reliable stream of data between computers. net.Listen opens a listener that waits for other programs to connect. Accept returns a connection to one client. A connection sends a stream of bytes, so both programs need a rule for where each message ends, such as a newline.

This line-based echo server handles each connection in its own goroutine, a function call started with go that can run while its caller continues. It sets a deadline so a stalled client cannot make the server wait forever.

package main
 
import (
    "bufio"
    "fmt"
    "net"
    "os"
    "time"
)
 
func main() {
    listener, err := net.Listen("tcp", "127.0.0.1:9000")
    if err != nil {
        panic(err)
    }
    defer listener.Close()
 
    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            return
        }
        go func() {
            defer conn.Close()
            if err := conn.SetDeadline(time.Now().Add(30 * time.Second)); err != nil {
                fmt.Fprintln(os.Stderr, err)
                return
            }
            scanner := bufio.NewScanner(conn)
            for scanner.Scan() {
                conn.SetDeadline(time.Now().Add(30 * time.Second))
                if _, err := fmt.Fprintln(conn, scanner.Text()); err != nil {
                    fmt.Fprintln(os.Stderr, err)
                    return
                }
            }
            if err := scanner.Err(); err != nil {
                fmt.Fprintln(os.Stderr, err)
            }
        }()
    }
}

In production

Set a limit on how many clients can connect at once, and check errors when reading and writing. A deadline is the time after which a read or write stops waiting. Scanner reads one line at a time and has a default maximum line size of about 64 KiB; choose another way to separate messages if lines can be longer.

Enjoyed this? Get more software craft delivered to your inbox.