- Go Web Development Cookbook
- Arpit Aggarwal
- 182字
- 2021-08-27 19:01:13
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\n" | 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:
- 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)
...
}
- Next, we defined the handleRequest function, which reads an incoming connection into the buffer until the first occurrence of \n 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('\n')
if err != nil
{
fmt.Println("Error reading:", err.Error())
}
fmt.Print("Message Received: ", string(message))
conn.Close()
}
推薦閱讀
- Mastering Machine Learning for Penetration Testing
- 物聯網識別技術
- 網絡創新指數研究
- 通信簡史:從信鴿到6G+
- 數字通信同步技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- React:Cross-Platform Application Development with React Native
- 網絡AI+:2030后的未來網絡
- 物聯網頂層設計與關鍵技術
- INSTANT LinkedIn Customization How-to
- 無線傳感器網絡定位技術
- 計算機網絡技術
- 網絡安全之道
- 物聯網
- 互聯網視覺設計(全彩慕課版)
- 天下一家:網絡聯通世界(科學新導向叢書)