How it works…

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

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

This apparently logs it to a server console, as shown in the following screenshot:

Let’s understand the change we introduced in this recipe:

  1. First, we called handleRequest from the main() method using the go keyword, which means we are invoking a function in a Goroutine, as follows:
func main() 
{
...
go handleRequest(conn)
...
}
  1. Next, we defined the handleRequest function, which reads an incoming connection into the buffer until the first occurrence of and prints the message on the console. If there are any errors in reading the message then it prints the error message along with the error object and finally closes the connection, as follows:
func handleRequest(conn net.Conn) 
{
message, err := bufio.NewReader(conn).ReadString(' ')
if err != nil
{
fmt.Println("Error reading:", err.Error())
}
fmt.Print("Message Received: ", string(message))
conn.Close()
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.194.57