- Go Web Development Cookbook
- Arpit Aggarwal
- 155字
- 2021-08-27 19:01:13
How to do it…
In this recipe, we are going to update the main() method to call a handleRequest method passing the connection object to read and print data on the server console. Perform the following steps:
- Create tcp-server-read-data.go and copy the following content:
package main
import
(
"bufio"
"fmt"
"log"
"net"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
CONN_TYPE = "tcp"
)
func main()
{
listener, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
if err != nil
{
log.Fatal("Error starting tcp server : ", err)
}
defer listener.Close()
log.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
for
{
conn, err := listener.Accept()
if err != nil
{
log.Fatal("Error accepting: ", err.Error())
}
go handleRequest(conn)
}
}
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 from the client: ", string(message))
conn.Close()
}
- Run the program with the following command:
$ go run tcp-server-read-data.go
推薦閱讀
- 物聯網工程規劃技術
- Building E-commerce Sites with VirtueMart Cookbook
- Spring Boot 2.0 Projects
- 網絡創新指數研究
- C/C++串口通信:典型應用實例編程實踐
- INSTANT KineticJS Starter
- 物聯網與智能家居
- Learning Node.js Development
- 轉化:提升網站流量和轉化率的技巧
- 精通SEO:100%網站流量提升密碼
- 圖解物聯網
- 區塊鏈技術與應用:打造分布式商業新生態
- 網絡信息安全工程技術與應用分析
- OSPF協議原理與功能拓展
- Hands-On Microservices:Monitoring and Testing