~/Concurrent TCP Server in Golang

Feb 15, 2022


To build a concurrent TCP server in Go, use goroutines so the server can handle multiple connections at once.

Here is a minimal example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import (
    "net"
    "fmt"
    "io"
)

func handleConn(conn net.Conn) {
    defer conn.Close()
    _, err := io.Copy(conn, conn) // Echo received data
    if err != nil {
        fmt.Println("Error:", err)
    }
}

func main() {
    ln, err := net.Listen("tcp", ":9000")
    if err != nil {
        panic(err)
    }
    for {
        conn, err := ln.Accept()
        if err != nil {
            continue
        }
        go handleConn(conn) // Handle each connection concurrently
    }
}

This code listens on port 9000. For every incoming connection, it starts a new goroutine to echo received data back (net.Conn). Goroutines are cheap threads managed by Go, making concurrency simple and efficient.

For more details, check the Go networking tutorial or Go by Example: TCP Server.

Tags: [golang] [tcp] [concurrency]