A TCP Server
This lesson introduces TCP servers and provides an implementation and detailed explanation of a TCP server and client in Go.
We'll cover the following...
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.
The server side #
The server-code resides in its own program as follows:
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() ...