Search⌘ K
AI Features

A TCP Server

Explore how to build a TCP server in Go that listens for client connections and handles each request in separate goroutines. Understand the use of the net package for TCP communication, managing connection errors, and structuring client-server interactions for efficient concurrent processing.

Go is very usable for writing web applications. Making HTML-screens with strings or templating is a good way to write apps that need a graphical interface.

A client-server application

We will develop a simple client-server application using the TCP-protocol and the goroutine paradigm from Chapter 12. A (web) server application has to respond to requests from many clients simultaneously. In Go, for every client-request, a goroutine is spawned to handle the request. We will need the package net for networking communication functionality. It contains methods for working with TCP/IP and UDP protocols, domain name resolution, and so on.

svg viewer

The server side

The server-code resides in its own program as follows:

Go (1.6.2)
package main
import (
"fmt"
"net"
)
func main() {
fmt.Println("Starting the server ...")
// create listener:
listener, err := net.Listen("tcp", "0.0.0.0:3001")
if err != nil {
fmt.Println("Error listening", err.Error())
return // terminate program
}
// listen and accept connections from clients:
for {
conn, err := listener.Accept()
if err != nil {
return // terminate program
}
go doServerStuff(conn)
}
}
func doServerStuff(conn net.Conn) {
for {
buf := make([]byte, 512)
_, err := conn.Read(buf)
if err != nil {
fmt.Println("Error reading", err.Error())
return // terminate program
}
fmt.Printf("Received data: %v", string(buf))
}
}

In main(), we make a net.Listener variable listener, which is the basic function of a server: to listen for and accept incoming client requests (on IP-address 0.0.0.0 on port 3001 via the TCP-protocol). This Listen() function can return a variable err of type error. The waiting for client requests is performed in an infinite for-loop with listener.Accept(). A client request makes a connection variable conn of type net.Conn. On this connection, a separate goroutine doServerStuff() is started which reads the incoming data in a buffer of size 512 bytes and outputs them on the server terminal; when all the data from the ...