Creating the TCP server
In the chapter Connect the Network, the client side of the TCP connection is presented. In this recipe, the server side will be described.
How to do it...
- Open the console and create the folder
chapter09/recipe01. - Navigate to the directory.
- Create the
servertcp.gofile with the following content:
package main
import (
"bufio"
"fmt"
"io"
"net"
)
func main() {
l, err := net.Listen("tcp", ":8080")
if err != nil {
panic(err)
}
for {
fmt.Println("Waiting for client...")
conn, err := l.Accept()
if err != nil {
panic(err)
}
msg, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
panic(err)
}
_, err = io.WriteString(conn, "Received: "+string(msg))
if err != nil {
fmt.Println(err)
...