- 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
推薦閱讀
- 計(jì)算機(jī)網(wǎng)絡(luò)與通信(第2版)
- 廣電5G從入門(mén)到精通
- EDA技術(shù)與VHDL編程
- GPS/GNSS原理與應(yīng)用(第3版)
- 網(wǎng)絡(luò)創(chuàng)新指數(shù)研究
- SD-WAN架構(gòu)與技術(shù)(第2版)
- 面向物聯(lián)網(wǎng)的嵌入式系統(tǒng)開(kāi)發(fā):基于CC2530和STM32微處理器
- 物聯(lián)網(wǎng)與無(wú)線傳感器網(wǎng)絡(luò)
- 網(wǎng)絡(luò)基礎(chǔ)與網(wǎng)絡(luò)管理項(xiàng)目化教程
- 物聯(lián)網(wǎng)長(zhǎng)距離無(wú)線通信技術(shù)應(yīng)用與開(kāi)發(fā)
- 2小時(shí)讀懂物聯(lián)網(wǎng)
- 智能物聯(lián)網(wǎng):區(qū)塊鏈與霧計(jì)算融合應(yīng)用詳解
- Python Web Scraping Cookbook
- ReasonML Quick Start Guide
- Architecting Data:Intensive Applications