官术网_书友最值得收藏!

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:

  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 \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()
}
主站蜘蛛池模板: 盈江县| 太原市| 鄢陵县| 屯留县| 宜城市| 富川| 济源市| 龙江县| 游戏| 都匀市| 吴川市| 西和县| 莲花县| 迁安市| 尚志市| 遂宁市| 西藏| 长汀县| 九寨沟县| 阿荣旗| 东安县| 措勤县| 陈巴尔虎旗| 临湘市| 茂名市| 台中县| 大兴区| 中阳县| 平湖市| 光泽县| 榕江县| 苍梧县| 远安县| 酉阳| 沙洋县| 钟祥市| 唐海县| 阿坝| 上犹县| 西吉县| 富阳市|