- 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
推薦閱讀
- 網絡云百問百答
- 物聯網智慧安監技術
- SOA用戶指南
- 從區塊鏈到Web3:構建未來互聯網生態
- SEO 20日
- 物聯網檢驗檢測技術
- Hands-On Full Stack Development with Spring Boot 2 and React(Second Edition)
- 工業互聯網創新實踐
- Python API Development Fundamentals
- NB-IoT原理和優化
- Enterprise ApplicationDevelopment with Ext JSand Spring
- 一本書讀懂移動物聯網
- Hands-On Cloud:Native Microservices with Jakarta EE
- 萬物互聯:物聯網核心技術與安全
- 網絡是怎樣連接的