...

/

A TCP Server

A TCP Server

This lesson introduces TCP servers and provides an implementation and detailed explanation of a TCP server and client in Go.

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:

Press + to interact
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 ...