TCP sockets

suggest change

TCP gives you a reliable, ordered stream of bytes between two programs. HTTP, SMTP, database protocols and Redis all run on top of it. In Go you work with TCP through package net:

API What it does
net.Listen("tcp", addr) opens a server socket and returns a net.Listener
ln.Accept() waits for the next client and returns a net.Conn
net.Dial("tcp", addr) connects to a server and returns a net.Conn
net.Dialer, net.ListenConfig same, with timeouts, contexts and socket options
conn.SetDeadline(t) makes blocked reads and writes fail after t

A net.Conn is an io.Reader and an io.Writer, so everything in io and bufio works on it: io.Copy, io.ReadFull, bufio.Scanner and so on. A net.Conn is safe to use from several goroutines, and the usual pattern is one goroutine per connection. Under the hood Go's runtime uses non-blocking sockets with epoll, kqueue or IOCP, so a blocked Read parks only the goroutine, not an OS thread.

The examples below start a server on 127.0.0.1:0. Port 0 tells the OS to pick any free port, and ln.Addr() tells you which one it picked. This lets each program run a server and a client in one process.

If you need HTTP, use net/http instead of raw sockets: see HTTP Server and HTTP Client.

Echo server and client

The smallest useful TCP program: the server echoes back whatever it reads, and the client sends a message and reads the reply.

package main

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

func handle(conn net.Conn, done chan<- struct{}) {
	defer close(done)
	defer conn.Close()
	fmt.Println("server: client connected")
	// copy everything we read back to the client, until the client closes
	n, err := io.Copy(conn, conn)
	fmt.Printf("server: echoed %d bytes, err: %v\n", n, err)
}

func main() {
	// port 0 asks the OS to pick a free port
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()
	fmt.Println("listening on", ln.Addr().Network())

	done := make(chan struct{})
	go func() {
		conn, err := ln.Accept()
		if err != nil {
			log.Fatal(err)
		}
		handle(conn, done)
	}()

	conn, err := net.Dial("tcp", ln.Addr().String())
	if err != nil {
		log.Fatal(err)
	}

	msg := []byte("hello, TCP")
	if _, err := conn.Write(msg); err != nil {
		log.Fatal(err)
	}

	buf := make([]byte, len(msg))
	if _, err := io.ReadFull(conn, buf); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("client: got %q\n", buf)

	conn.Close() // server's io.Copy sees EOF and returns
	<-done
}
listening on tcp
server: client connected
client: got "hello, TCP"
server: echoed 10 bytes, err: <nil>

Things to note:

A real server runs the accept loop forever and handles each client in its own goroutine:

for {
	conn, err := ln.Accept()
	if errors.Is(err, net.ErrClosed) {
		return // listener was closed
	}
	if err != nil {
		log.Println("accept:", err)
		continue
	}
	go handle(conn)
}

TCP is a stream, not messages

The most common TCP bug is assuming that one Write on one side arrives as one Read on the other. TCP doesn't preserve message boundaries. Two writes of 5 bytes can arrive as one read of 10 bytes, and a 10 KB write can arrive as several smaller reads. conn.Read(buf) returns as soon as some data is available, and n may be smaller than len(buf).

So every protocol needs framing: a way to tell where one message ends and the next begins. The two common approaches are delimiters (usually newlines) and length prefixes.

Line-based protocol

Text protocols like SMTP, Redis and memcached use one command per line. bufio.Scanner splits the stream into lines for you, and bufio.Writer batches small writes:

package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"strings"
)

func handle(conn net.Conn) {
	defer conn.Close()
	r := bufio.NewScanner(conn)
	w := bufio.NewWriter(conn)
	for r.Scan() {
		cmd, arg, _ := strings.Cut(r.Text(), " ")
		switch strings.ToUpper(cmd) {
		case "UPPER":
			fmt.Fprintln(w, "OK", strings.ToUpper(arg))
		case "REVERSE":
			b := []rune(arg)
			for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
				b[i], b[j] = b[j], b[i]
			}
			fmt.Fprintln(w, "OK", string(b))
		case "QUIT":
			fmt.Fprintln(w, "BYE")
			w.Flush()
			return
		default:
			fmt.Fprintln(w, "ERR unknown command", cmd)
		}
		// without Flush the reply would sit in the buffer
		if err := w.Flush(); err != nil {
			return
		}
	}
}

func main() {
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()
	go func() {
		for {
			conn, err := ln.Accept()
			if err != nil {
				return
			}
			go handle(conn)
		}
	}()

	conn, err := net.Dial("tcp", ln.Addr().String())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	r := bufio.NewReader(conn)
	for _, line := range []string{"upper hello", "reverse gopher", "jump", "quit"} {
		fmt.Fprintf(conn, "%s\n", line)
		reply, err := r.ReadString('\n')
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-16s -> %s", line, reply)
	}
}
upper hello      -> OK HELLO
reverse gopher   -> OK rehpog
jump             -> ERR unknown command jump
quit             -> BYE

bufio.Writer keeps data in memory until the buffer fills up or you call Flush. Forgetting to flush is a classic cause of a client that hangs waiting for a reply.

bufio.Scanner has a default maximum line length of 64 KB. A longer line makes Scan return false and Err return bufio.ErrTooLong. Raise the limit with sc.Buffer(make([]byte, 0, 64*1024), maxLen). Always keep some limit: without one, a client that never sends a newline makes the server buffer data forever.

Length-prefixed messages

For binary data, send the length of each message before the message itself. Here a 4-byte big-endian length is followed by the payload:

package main

import (
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
)

const maxMsgSize = 1 << 20 // 1 MB

// writeMsg sends a 4-byte big-endian length followed by the payload.
func writeMsg(w io.Writer, payload []byte) error {
	if len(payload) > maxMsgSize {
		return errors.New("message too large")
	}
	buf := make([]byte, 4+len(payload))
	binary.BigEndian.PutUint32(buf, uint32(len(payload)))
	copy(buf[4:], payload)
	_, err := w.Write(buf)
	return err
}

// readMsg reads one length-prefixed message.
func readMsg(r io.Reader) ([]byte, error) {
	var hdr [4]byte
	if _, err := io.ReadFull(r, hdr[:]); err != nil {
		return nil, err
	}
	n := binary.BigEndian.Uint32(hdr[:])
	if n > maxMsgSize {
		return nil, fmt.Errorf("message size %d exceeds limit", n)
	}
	payload := make([]byte, n)
	if _, err := io.ReadFull(r, payload); err != nil {
		return nil, err
	}
	return payload, nil
}

func main() {
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()

	done := make(chan struct{})
	go func() {
		defer close(done)
		conn, err := ln.Accept()
		if err != nil {
			return
		}
		defer conn.Close()
		for {
			msg, err := readMsg(conn)
			if errors.Is(err, io.EOF) {
				fmt.Println("server: client closed the connection")
				return
			}
			if err != nil {
				fmt.Println("server: error:", err)
				return
			}
			fmt.Printf("server: got %d bytes: %q\n", len(msg), msg)
		}
	}()

	conn, err := net.Dial("tcp", ln.Addr().String())
	if err != nil {
		log.Fatal(err)
	}
	// three messages, written back to back; TCP may deliver them
	// in one chunk but the framing keeps them apart
	for _, s := range []string{"first", "", "third message, a bit longer"} {
		if err := writeMsg(conn, []byte(s)); err != nil {
			log.Fatal(err)
		}
	}
	conn.Close()
	<-done
}
server: got 5 bytes: "first"
server: got 0 bytes: ""
server: got 27 bytes: "third message, a bit longer"
server: client closed the connection

io.ReadFull keeps calling Read until the buffer is full. It returns io.EOF if the connection closes before any bytes were read and io.ErrUnexpectedEOF if it closes in the middle, so you can tell a clean disconnect from a truncated message.

Always check the length against a limit before allocating. Otherwise a client can send 0xFFFFFFFF as the length and make you allocate 4 GB.

writeMsg builds the header and payload in one buffer and calls Write once. Two separate writes would also be correct, but may send two small packets. For structured messages, put JSON, gob or protobuf inside the frame.

Timeouts and deadlines

By default Read and Write block forever. A client that connects and goes silent holds a goroutine and a socket until the server restarts. Deadlines fix this:

package main

import (
	"errors"
	"fmt"
	"log"
	"net"
	"os"
	"time"
)

func main() {
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()
	// a server that accepts connections but never writes anything
	go func() {
		for {
			conn, err := ln.Accept()
			if err != nil {
				return
			}
			_ = conn // leak on purpose: keep it open, stay silent
		}
	}()

	conn, err := net.DialTimeout("tcp", ln.Addr().String(), 2*time.Second)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
	buf := make([]byte, 16)
	start := time.Now()
	_, err = conn.Read(buf)
	fmt.Printf("read returned after ~%dms\n", time.Since(start).Round(50*time.Millisecond).Milliseconds())
	fmt.Println("err:", err)
	fmt.Println("is deadline exceeded:", errors.Is(err, os.ErrDeadlineExceeded))

	var ne net.Error
	if errors.As(err, &ne) {
		fmt.Println("net.Error timeout:", ne.Timeout())
	}

	// a zero time clears the deadline
	conn.SetReadDeadline(time.Time{})
}
read returned after ~100ms
err: read tcp 127.0.0.1:56716->127.0.0.1:56715: i/o timeout
is deadline exceeded: true
net.Error timeout: true

A deadline is an absolute point in time, not a per-call timeout. Once it passes, every Read fails until you set a new deadline. To get an idle timeout, set the deadline again before each read, as the graceful shutdown example below does. A zero time.Time removes the deadline.

Check for a timeout with errors.Is(err, os.ErrDeadlineExceeded). The older approach of asserting net.Error and calling Timeout() also works.

net.DialTimeout limits how long connecting can take. Without it, connecting to a host that silently drops packets can block for a minute or more, until the OS gives up.

Dial errors and contexts

net.Dialer is the configurable version of net.Dial. Its DialContext method takes a context, which limits the whole operation including the DNS lookup, and lets you cancel a dial in progress. See Context.

Errors from package net are usually a *net.OpError that wraps the underlying cause:

package main

import (
	"context"
	"errors"
	"fmt"
	"net"
	"time"
)

func main() {
	// grab a free port, then close it so nothing listens there
	ln, _ := net.Listen("tcp", "127.0.0.1:0")
	addr := ln.Addr().String()
	ln.Close()

	_, err := net.Dial("tcp", addr)
	var opErr *net.OpError
	if errors.As(err, &opErr) {
		fmt.Println("op:", opErr.Op, "net:", opErr.Net, "timeout:", opErr.Timeout())
		fmt.Println("cause:", opErr.Err)
	}

	// a context bounds the whole dial: DNS lookup plus connect
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	var d net.Dialer
	_, err = d.DialContext(ctx, "tcp", "no-such-host.invalid:80")
	var dnsErr *net.DNSError
	if errors.As(err, &dnsErr) {
		fmt.Println("dns error for", dnsErr.Name, "not found:", dnsErr.IsNotFound)
	}
}
op: dial net: tcp timeout: false
cause: connectex: No connection could be made because the target machine actively refused it.
dns error for no-such-host.invalid not found: true

The output above is from Windows. On Linux and macOS the cause reads connect: connection refused, and errors.Is(err, syscall.ECONNREFUSED) is true. Name resolution failures are a *net.DNSError.

When a host name resolves to several addresses, Dial tries them in turn. For hosts with both IPv4 and IPv6 addresses it races the two families ("Happy Eyeballs"), so you don't have to.

Graceful shutdown

A production server needs to stop cleanly: stop accepting new clients, close existing connections and wait for handler goroutines to finish. Closing the listener makes a blocked Accept return an error that matches net.ErrClosed:

package main

import (
	"bufio"
	"context"
	"errors"
	"fmt"
	"log"
	"net"
	"os/signal"
	"strings"
	"sync"
	"syscall"
	"time"
)

type Server struct {
	ln    net.Listener
	wg    sync.WaitGroup
	mu    sync.Mutex
	conns map[net.Conn]struct{}
}

func (s *Server) Serve() error {
	for {
		conn, err := s.ln.Accept()
		if errors.Is(err, net.ErrClosed) {
			return nil // Shutdown was called
		}
		if err != nil {
			return err
		}
		s.mu.Lock()
		s.conns[conn] = struct{}{}
		s.mu.Unlock()
		s.wg.Go(func() {
			s.handle(conn)
			s.mu.Lock()
			delete(s.conns, conn)
			s.mu.Unlock()
		})
	}
}

func (s *Server) handle(conn net.Conn) {
	defer conn.Close()
	sc := bufio.NewScanner(conn)
	for {
		// drop clients that are idle for too long
		conn.SetReadDeadline(time.Now().Add(30 * time.Second))
		if !sc.Scan() {
			return
		}
		fmt.Fprintln(conn, strings.ToUpper(sc.Text()))
	}
}

// Shutdown stops accepting, closes open connections and waits for handlers.
func (s *Server) Shutdown() {
	s.ln.Close()
	s.mu.Lock()
	for c := range s.conns {
		c.Close()
	}
	s.mu.Unlock()
	s.wg.Wait()
}

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	s := &Server{ln: ln, conns: map[net.Conn]struct{}{}}

	serveErr := make(chan error, 1)
	go func() { serveErr <- s.Serve() }()

	// a client that connects and then just sits there
	conn, err := net.Dial("tcp", ln.Addr().String())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Fprintln(conn, "hi")
	reply, _ := bufio.NewReader(conn).ReadString('\n')
	fmt.Print("client got: ", reply)

	// in a real program you'd wait for Ctrl+C: <-ctx.Done()
	// here we simulate it with a short timeout
	select {
	case <-ctx.Done():
	case <-time.After(100 * time.Millisecond):
	}

	s.Shutdown()
	fmt.Println("serve returned:", <-serveErr)

	_, err = conn.Read(make([]byte, 1))
	fmt.Println("client read after shutdown:", err)
}
client got: HI
serve returned: <nil>
client read after shutdown: EOF

Details:

If you'd rather let in-flight requests finish, close only the listener, wait on the WaitGroup with a timeout, and force-close the remaining connections when the timeout expires.

Half-close with CloseWrite

Sometimes the client needs to say "I'm done sending" while still waiting for a reply. Close would also close the read side. (*net.TCPConn).CloseWrite shuts down only the write side, so the server sees io.EOF but can still write back:

package main

import (
	"fmt"
	"io"
	"log"
	"net"
	"strings"
)

func main() {
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()

	// server: read the whole request until EOF, then reply
	go func() {
		conn, err := ln.Accept()
		if err != nil {
			return
		}
		defer conn.Close()
		data, err := io.ReadAll(conn)
		if err != nil {
			return
		}
		fmt.Fprintf(conn, "received %d bytes, %d words", len(data), len(strings.Fields(string(data))))
	}()

	conn, err := net.Dial("tcp", ln.Addr().String())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	io.WriteString(conn, "the quick brown fox jumps over the lazy dog")

	// signal "no more data" but keep the read side open
	tcpConn := conn.(*net.TCPConn)
	if err := tcpConn.CloseWrite(); err != nil {
		log.Fatal(err)
	}

	reply, err := io.ReadAll(conn)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(reply))
}
received 43 bytes, 9 words

net.Dial("tcp", ...) returns a *net.TCPConn behind the net.Conn interface, so the type assertion is safe. CloseRead is the counterpart for the read side.

Socket options

net.ListenConfig and net.Dialer configure sockets before they are used, and *net.TCPConn has setters for an open connection:

package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net"
	"time"
)

func main() {
	// ListenConfig configures keep-alive for accepted connections
	lc := net.ListenConfig{
		KeepAliveConfig: net.KeepAliveConfig{
			Enable:   true,
			Idle:     30 * time.Second, // idle time before the first probe
			Interval: 10 * time.Second, // time between probes
			Count:    3,                // unanswered probes before giving up
		},
	}
	ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()
	go func() {
		c, err := ln.Accept()
		if err != nil {
			return
		}
		defer c.Close()
		io.Copy(io.Discard, c)
	}()

	d := net.Dialer{
		Timeout: 5 * time.Second,
		KeepAliveConfig: net.KeepAliveConfig{
			Enable: true,
			Idle:   time.Minute,
		},
	}
	conn, err := d.Dial("tcp", ln.Addr().String())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	tc := conn.(*net.TCPConn)
	// Go disables Nagle's algorithm by default (NoDelay is true)
	// re-enable it if you send many tiny writes and prefer fewer packets
	if err := tc.SetNoDelay(false); err != nil {
		log.Fatal(err)
	}
	if err := tc.SetReadBuffer(256 * 1024); err != nil {
		log.Fatal(err)
	}
	if err := tc.SetWriteBuffer(256 * 1024); err != nil {
		log.Fatal(err)
	}

	local := tc.LocalAddr().(*net.TCPAddr)
	remote := tc.RemoteAddr().(*net.TCPAddr)
	fmt.Println("local IP:", local.IP, "remote IP:", remote.IP)
	fmt.Println("same port as listener:", remote.Port == ln.Addr().(*net.TCPAddr).Port)
}
local IP: 127.0.0.1 remote IP: 127.0.0.1
same port as listener: true

Speaking an existing protocol

Many protocols are text over TCP, so you can implement a client with nothing more than net.Dial and bufio. Here we send an HTTP/1.1 request by hand to a local net/http server and parse the response with net/textproto:

package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"net/http/httptest"
	"net/textproto"
	"strings"
)

func main() {
	// a regular HTTP server on a random local port
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "hello from %s %s", r.Method, r.URL.Path)
	}))
	defer srv.Close()
	addr := strings.TrimPrefix(srv.URL, "http://")

	conn, err := net.Dial("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	// HTTP/1.1 is a text protocol, so we can write a request by hand
	fmt.Fprintf(conn, "GET /raw HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", addr)

	tp := textproto.NewReader(bufio.NewReader(conn))
	status, err := tp.ReadLine()
	if err != nil {
		log.Fatal(err)
	}
	hdr, err := tp.ReadMIMEHeader()
	if err != nil {
		log.Fatal(err)
	}
	body, err := io.ReadAll(tp.R)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(status)
	fmt.Println("Content-Length:", hdr.Get("Content-Length"))
	fmt.Println("Content-Type:", hdr.Get("Content-Type"))
	fmt.Printf("body: %q\n", body)
}
HTTP/1.1 200 OK
Content-Length: 19
Content-Type: text/plain; charset=utf-8
body: "hello from GET /raw"

net/textproto handles the line-and-header format shared by HTTP, SMTP, NNTP and others. In practice you'd use net/http for HTTP and net/smtp for email, but the same approach works for any text protocol that lacks a Go library.

For TLS, wrap the connection with crypto/tls: tls.Dial("tcp", addr, cfg) on the client and tls.Listen or tls.NewListener(ln, cfg) on the server. The result is still a net.Conn, so the rest of your code stays the same. See Create an HTTPS server for working with certificates.

Testing with net.Pipe

Write connection handlers against the net.Conn interface, not *net.TCPConn, and you can test them without a network. net.Pipe returns two connected in-memory net.Conn ends:

package main

import (
	"bufio"
	"fmt"
	"net"
	"strings"
)

// handle is the code under test; it only depends on net.Conn
func handle(conn net.Conn) {
	defer conn.Close()
	sc := bufio.NewScanner(conn)
	for sc.Scan() {
		fmt.Fprintln(conn, strings.ToUpper(sc.Text()))
	}
}

func main() {
	client, server := net.Pipe()
	go handle(server)

	r := bufio.NewReader(client)
	for _, s := range []string{"ping", "net.Pipe is synchronous"} {
		fmt.Fprintln(client, s)
		line, _ := r.ReadString('\n')
		fmt.Print(line)
	}
	client.Close()
}
PING
NET.PIPE IS SYNCHRONOUS

net.Pipe is synchronous and unbuffered: a Write blocks until the other side has read all of it. A handler that writes several replies before reading can deadlock in a test even though it works over TCP, where the kernel buffers data. If that happens, use a real listener on 127.0.0.1:0 in the test instead; it's fast and needs no setup. See Testing.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents