How it works...

Once we run the program, the TCP server will start locally listening on port 8080. Execute an echo command from the command line, as follows:

$ echo -n "Hello to TCP server\n" | nc localhost 8080

This will give us the following response from the server:

Hello to TCP server

Let’s look at the changes we introduced in this recipe to write data to the client. Everything in handleRequest is exactly the same as in the previous recipe except we introduced a new line that writes data as a byte array to the connection, as follows:

func handleRequest(conn net.Conn) {  ...  conn.Write([]byte(message + "\n"))  ...}

Get Go Web Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.