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

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()
}
主站蜘蛛池模板: 温泉县| 阿克苏市| 田阳县| 江达县| 广汉市| 莆田市| 凌源市| 哈密市| 关岭| 苍南县| 贺兰县| 仪陇县| 江阴市| 陇西县| 七台河市| 达日县| 盘山县| 驻马店市| 中宁县| 收藏| 贵南县| 汾阳市| 寻乌县| 会东县| 临泽县| 正蓝旗| 高尔夫| 大埔区| 墨竹工卡县| 朝阳市| 东乌珠穆沁旗| 介休市| 时尚| 财经| 西乌珠穆沁旗| 新竹市| 板桥市| 南丹县| 义乌市| 望都县| 镇巴县|