Go socket
last modified November 19, 2026 Go 1.27
In this article we show how to work with TCP sockets in Go. We write servers
and clients with the net package, read lines from a connection,
serve several clients at once, set deadlines, frame messages and send a raw
HTTP request.
A socket is an endpoint of a two-way communication link between two programs
running on a network. Socket programming is low-level: the program decides
what bytes to send and how to tell where a message ends. Higher-level packages
such as net/http are built on top of it.
127.0.0.1:5050.
All examples in this article were compiled and run with Go 1.27.0 on Linux. The servers listen on the loopback address, so the examples need no network access and their outputs can be reproduced.
TCP and the net package
TCP provides a reliable, ordered and error-checked stream of bytes between two programs. Services such as HTTP, SMTP or SSH run on TCP. UDP sends independent packets with no guarantee of arrival or order; it is used where speed matters more than reliability, for example for DNS or VoIP. This article covers TCP; the UDP article covers UDP.
The net package provides a portable interface for network I/O. A
server calls net.Listen to open a listening socket and
Accept to wait for clients; a client calls net.Dial.
Both sides then get a net.Conn, which is an
io.Reader and an io.Writer.
The first argument of Listen and Dial is the network
name: tcp, tcp4 and tcp6 for TCP,
udp, udp4 and udp6 for UDP, and
unix, unixgram and unixpacket for Unix
domain sockets. For TCP the address has the form host:port; the
host is an IP address or a name that resolves to one.
A TCP server
The first server sends a quote to every client that connects and then closes the connection.
package main
import (
"fmt"
"log"
"net"
)
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:5050")
if err != nil {
log.Fatal(err)
}
defer ln.Close()
fmt.Println("Listening on", ln.Addr())
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
fmt.Fprintln(conn, "Simplicity is prerequisite for reliability.")
conn.Close()
}
}
The server listens on port 5050 of the loopback interface and handles one client after another.
ln, err := net.Listen("tcp", "127.0.0.1:5050")
net.Listen creates a listening socket. With the
127.0.0.1 address, only programs on the same machine can connect;
an address such as :5050 would listen on all interfaces.
conn, err := ln.Accept()
Accept blocks until a client connects and returns a new
connection for it. The listener keeps listening for more clients.
fmt.Fprintln(conn, "Simplicity is prerequisite for reliability.") conn.Close()
Since the connection is an io.Writer, we can write to it with
fmt.Fprintln. Closing the connection tells the client that no more
data will come.
The server runs until we stop it with Ctrl+C. We start it in one terminal and run the clients of the next sections in another one.
$ go run quote_server.go Listening on 127.0.0.1:5050
A TCP client
The client connects to the quote server and reads everything it sends.
package main
import (
"fmt"
"io"
"log"
"net"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:5050")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
fmt.Println("Connected to", conn.RemoteAddr())
data, err := io.ReadAll(conn)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(data))
}
net.Dial connects to the server and returns the client side of
the connection.
data, err := io.ReadAll(conn)
io.ReadAll reads until the server closes the connection. It
works here because the server closes the connection after the quote; with a
server that keeps the connection open, it would block.
$ go run quote_client.go Connected to 127.0.0.1:5050 Simplicity is prerequisite for reliability.
A refused connection
When no program listens on the port, the operating system refuses the
connection and Dial returns an error.
package main
import (
"errors"
"fmt"
"net"
"syscall"
"time"
)
func main() {
_, err := net.DialTimeout("tcp", "127.0.0.1:5051", 2*time.Second)
fmt.Println(err)
if errors.Is(err, syscall.ECONNREFUSED) {
fmt.Println("no server is listening on port 5051")
}
var opErr *net.OpError
if errors.As(err, &opErr) {
fmt.Println("operation:", opErr.Op)
fmt.Println("address:", opErr.Addr)
}
}
net.DialTimeout works like Dial but gives up after
the given time; this matters for hosts that do not answer at all. A refused
connection fails at once.
if errors.Is(err, syscall.ECONNREFUSED) {
The error wraps the system error, so errors.Is can test for
syscall.ECONNREFUSED.
var opErr *net.OpError
if errors.As(err, &opErr) {
Network operations return a *net.OpError, which holds the
failed operation and the remote address.
$ go run refused.go dial tcp 127.0.0.1:5051: connect: connection refused no server is listening on port 5051 operation: dial address: 127.0.0.1:5051
Reading from the client
The next server keeps the connection open and reads lines from the client. It answers every line with its uppercase version.
package main
import (
"bufio"
"fmt"
"log"
"net"
"strings"
)
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:5050")
if err != nil {
log.Fatal(err)
}
defer ln.Close()
fmt.Println("Listening on", ln.Addr())
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
handle(conn)
}
}
func handle(conn net.Conn) {
defer conn.Close()
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
line := scanner.Text()
fmt.Fprintln(conn, strings.ToUpper(line))
}
if err := scanner.Err(); err != nil {
log.Println(err)
}
}
The work with a single client is moved to the handle function.
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
line := scanner.Text()
fmt.Fprintln(conn, strings.ToUpper(line))
}
TCP delivers a stream of bytes, not lines. A bufio.Scanner reads
the stream and splits it at newline characters. Scan returns
false when the client closes the connection or when reading fails; in the
second case scanner.Err returns the error.
$ go run upper_server.go Listening on 127.0.0.1:5050
A line client
The client sends three words, one per line, and reads a reply after each one.
package main
import (
"bufio"
"fmt"
"log"
"net"
"strings"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:5050")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
reader := bufio.NewReader(conn)
words := []string{"falcon", "sky", "cloud"}
for _, word := range words {
fmt.Fprintln(conn, word)
reply, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s -> %s\n", word, strings.TrimSpace(reply))
}
}
The client and the server agree on a simple protocol: every request and every reply is one line of text.
reader := bufio.NewReader(conn)
The reader is created once, before the loop. A bufio.Reader may
read more bytes from the connection than it returns; a new reader for every
reply could lose the buffered data.
reply, err := reader.ReadString('\n')
ReadString returns the data up to and including the newline,
which strings.TrimSpace removes.
$ go run upper_client.go falcon -> FALCON sky -> SKY cloud -> CLOUD
Several clients at once
The uppercase server handles one connection at a time. While a client stays connected, the others have to wait. The following program starts four clients at the same time; each keeps its connection open for 500 ms after the reply.
package main
import (
"bufio"
"fmt"
"log"
"net"
"strings"
"sync"
"time"
)
func ask(word string) string {
conn, err := net.Dial("tcp", "127.0.0.1:5050")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
fmt.Fprintln(conn, word)
reply, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
log.Fatal(err)
}
// keep the connection open for a while, as a real client would
time.Sleep(500 * time.Millisecond)
return strings.TrimSpace(reply)
}
func main() {
words := []string{"falcon", "sky", "cloud", "forest"}
replies := make([]string, len(words))
start := time.Now()
var wg sync.WaitGroup
for i, word := range words {
wg.Go(func() {
replies[i] = ask(word)
})
}
wg.Wait()
fmt.Println(replies)
fmt.Println("elapsed:", time.Since(start).Round(100*time.Millisecond))
}
The ask function connects, sends a word, reads the reply and
waits before it closes the connection.
for i, word := range words {
wg.Go(func() {
replies[i] = ask(word)
})
}
WaitGroup.Go, added in Go 1.25, runs each client in its own
goroutine and waits for it in Wait. Every
goroutine writes to its own slice element, so the replies stay in order
without a mutex. See the WaitGroup article
for details.
We run the program against the uppercase server from the previous section.
$ go run concurrent_client.go [FALCON SKY CLOUD FOREST] elapsed: 2s
A goroutine per connection
The four clients took two seconds because the server served them one after
another. To serve them concurrently, the server runs handle in a
new goroutine. This is the only change in concurrent_server.go
against upper_server.go:
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go handle(conn)
}
The main goroutine returns to Accept immediately, while each
connection is served by its own goroutine. Goroutines are cheap, so this
pattern scales to thousands of connections. A handler that touches shared
data must protect it, for example with a mutex.
We start concurrent_server.go in place of the uppercase server
and run the same client again.
$ go run concurrent_client.go [FALCON SKY CLOUD FOREST] elapsed: 500ms
Deadlines
A client that connects and then sends nothing ties up a goroutine and a socket forever. A deadline limits how long a read or write may block. This server closes connections that are idle for more than two seconds.
package main
import (
"bufio"
"errors"
"fmt"
"log"
"net"
"os"
"strings"
"time"
)
const idleTimeout = 2 * time.Second
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:5050")
if err != nil {
log.Fatal(err)
}
defer ln.Close()
fmt.Println("Listening on", ln.Addr())
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go handle(conn)
}
}
func handle(conn net.Conn) {
defer conn.Close()
scanner := bufio.NewScanner(conn)
for {
conn.SetReadDeadline(time.Now().Add(idleTimeout))
if !scanner.Scan() {
break
}
fmt.Fprintln(conn, strings.ToUpper(scanner.Text()))
}
err := scanner.Err()
if errors.Is(err, os.ErrDeadlineExceeded) {
fmt.Fprintln(conn, "idle for too long, bye")
return
}
if err != nil {
log.Println(err)
}
}
The main function is the same as in the concurrent server; the
new code is in handle.
conn.SetReadDeadline(time.Now().Add(idleTimeout))
A deadline is an absolute point in time, not a duration. To get an idle timeout, we move the deadline forward before every read. A read that is still blocked when the deadline passes fails.
if errors.Is(err, os.ErrDeadlineExceeded) {
fmt.Fprintln(conn, "idle for too long, bye")
return
}
A read that hits the deadline returns an error that wraps
os.ErrDeadlineExceeded. The read deadline does not affect
writing, so the server can still say goodbye. SetWriteDeadline
and SetDeadline set the deadline for writes and for both
directions.
The client sends one line and then waits for the server.
package main
import (
"fmt"
"io"
"log"
"net"
"time"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:5050")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
start := time.Now()
fmt.Fprintln(conn, "hello")
// the client sends nothing more and waits for the server
data, err := io.ReadAll(conn)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(data))
fmt.Println("closed after", time.Since(start).Round(100*time.Millisecond))
}
io.ReadAll returns when the server closes the connection, which
happens two seconds after the last line from the client.
$ go run idle_server.go Listening on 127.0.0.1:5050
$ go run idle_client.go HELLO idle for too long, bye closed after 2s
Message framing
TCP does not keep message boundaries. Two writes on one side can arrive as a single read on the other side, and one write can arrive in several parts. The newline protocol works for text without newlines; for any data, a common solution is a length prefix. Each frame starts with four bytes holding the length of the payload, followed by the payload.
package main
import (
"encoding/binary"
"log"
"net"
)
func writeFrame(conn net.Conn, msg string) error {
buf := make([]byte, 4+len(msg))
binary.BigEndian.PutUint32(buf, uint32(len(msg)))
copy(buf[4:], msg)
_, err := conn.Write(buf)
return err
}
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:5050")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
msgs := []string{"an old falcon", "", "a line\nwith two parts"}
for _, msg := range msgs {
if err := writeFrame(conn, msg); err != nil {
log.Fatal(err)
}
}
}
The client sends three messages directly after each other. The second one is empty and the third one contains a newline, so a line protocol could not carry them.
buf := make([]byte, 4+len(msg)) binary.BigEndian.PutUint32(buf, uint32(len(msg))) copy(buf[4:], msg)
The length is stored in big-endian order, the usual byte order for network
protocols. Header and payload are written with a single Write.
The server reads the frames back.
package main
import (
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
)
const maxFrame = 1 << 16
func readFrame(conn net.Conn) (string, error) {
var header [4]byte
if _, err := io.ReadFull(conn, header[:]); err != nil {
return "", err
}
size := binary.BigEndian.Uint32(header[:])
if size > maxFrame {
return "", fmt.Errorf("frame too large: %d bytes", size)
}
payload := make([]byte, size)
if _, err := io.ReadFull(conn, payload); err != nil {
return "", err
}
return string(payload), nil
}
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:5050")
if err != nil {
log.Fatal(err)
}
defer ln.Close()
fmt.Println("Listening on", ln.Addr())
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go handle(conn)
}
}
func handle(conn net.Conn) {
defer conn.Close()
for {
msg, err := readFrame(conn)
if errors.Is(err, io.EOF) {
return
}
if err != nil {
log.Println(err)
return
}
fmt.Printf("%d bytes: %q\n", len(msg), msg)
}
}
The readFrame function reads the header, then exactly as many
bytes as the header announces.
if _, err := io.ReadFull(conn, header[:]); err != nil {
A plain Read may return fewer bytes than the buffer holds.
io.ReadFull keeps reading until the buffer is full. It returns
io.EOF when the connection closes before the first byte, which
handle treats as the normal end of the conversation, and
io.ErrUnexpectedEOF when it closes in the middle of a frame.
if size > maxFrame {
return "", fmt.Errorf("frame too large: %d bytes", size)
}
The length comes from the network, so the server checks it before it allocates the buffer. Without the check, a client could make the server allocate up to 4 GB with four bytes.
We start the server and run the client in another terminal. The server prints the three messages as they were sent.
$ go run frame_client.go
$ go run frame_server.go Listening on 127.0.0.1:5050 13 bytes: "an old falcon" 0 bytes: "" 21 bytes: "a line\nwith two parts"
An HTTP test server
HTTP is a text protocol on top of TCP, so we can speak it over a plain socket.
For the next example we use a small HTTP server that reports the method, the path
and the User-Agent of the request.
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// remove the Date header to keep the output stable
w.Header()["Date"] = nil
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintf(w, "%s %s from %s\n", r.Method, r.URL.Path, r.UserAgent())
})
fmt.Println("Listening on 127.0.0.1:8080")
log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}
Setting the Date header to nil stops
net/http from adding it, so the response is the same on every
run.
$ go run http_server.go Listening on 127.0.0.1:8080
A raw HTTP request
The client connects to the test server, writes the request line and the headers by hand and prints the raw response.
package main
import (
"fmt"
"io"
"log"
"net"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:8080")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
req := "GET /about HTTP/1.1\r\n" +
"Host: 127.0.0.1:8080\r\n" +
"User-Agent: go-socket\r\n" +
"Connection: close\r\n" +
"\r\n"
if _, err := io.WriteString(conn, req); err != nil {
log.Fatal(err)
}
res, err := io.ReadAll(conn)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(res))
}
Every line of an HTTP request ends with \r\n, and an empty line
ends the headers. The Host header is required in HTTP/1.1.
"Connection: close\r\n" +
HTTP/1.1 keeps connections open by default. With
Connection: close, the server closes the connection after the
response, so io.ReadAll returns. The message format is described
in RFC 9112.
$ go run raw_http.go HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Content-Length: 26 Connection: close GET /about from go-socket
Source
Go net package - reference
Go bufio package - reference
Go encoding/binary package - reference
In this article we have worked with TCP sockets in Go: a server and a client,
connection errors, a line protocol, a goroutine per connection, deadlines,
length-prefixed frames and a raw HTTP request. The
HTTP client and
HTTP server articles show the
net/http package, the email
article sends mail over SMTP, and the WebSocket
article covers a message protocol for the browser.
Author
List all Go tutorials.