Go Socket Programming Made Simple

Go Socket Programming Made Simple

Go wraps C’s socket system calls into fewer, more usable APIs.

TCP Programming

The traditional socket, bind, and listen calls merge into one:

net.Listen("tcp", ":8080")

This returns a net.TCPListener. The second parameter binds to any IP when you don’t specify one (matches all by default).

The listener interface isolates the underlying implementation:

type Listener interface {
	Accept() (conn, error)
	Close() error
	Addr() Addr
}

Each accepted connection also uses an interface for abstraction:

type Conn interface {
	Read(b []byte) (n int, err error)
	Write(b []byte) (n int, err error)
	Close() error
}

You can set timeout values for each connection:

conn.SetDeadline(t time.Time) // Sets timeout for current connection I/O operations (read, write, etc.), only for this connection!

conn.SetReadDeadline(t time.Time)
conn.SetWriteDeadline(t time.Time)
// Note: even if a write operation times out, it doesn't mean the write failed completely. The first return value from write (bytes written) may still be greater than 0.

UDP Programming

net.ListenPacket("udp", ":8080")

net.PacketConn can call ReadFrom to get data and can be used with WriteTo.

Port Conflicts

Multiple sockets bound to the same port cause port conflicts.

Solutions: Socket options customize socket behavior. Setting the SO_REUSEADDR option lets identical protocols bind to the same port. The system allocates based on the bound IP address.

You can define socket options in the ListenConfig struct and pass them to the listener. Use the rawConn.Control callback to customize socket options. Different operating systems implement options differently, so use unix.SetsockoptInt.