- Go Web Development Cookbook
- Arpit Aggarwal
- 147字
- 2021-08-27 19:01:13
How to do it…
In this recipe, we are going to update the handleRequest method in the program to write data back to the client. Perform the following steps:
- Create tcp-server-write-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:", string(message))
conn.Write([]byte(message + "\n"))
conn.Close()
}
- Run the program with the following command:
$ go run tcp-server-write-data.go
推薦閱讀
- CorelDRAW X6 中文版圖形設(shè)計實戰(zhàn)從入門到精通
- 數(shù)據(jù)通信網(wǎng)絡(luò)實踐:基礎(chǔ)知識與交換機技術(shù)
- 無人機通信
- WordPress 5 Complete
- 物聯(lián)網(wǎng)通信技術(shù)
- Building Web Applications with ArcGIS
- Echo Quick Start Guide
- 互聯(lián)網(wǎng)+思維與創(chuàng)新:通往未來的+號
- 異構(gòu)蜂窩網(wǎng)絡(luò)關(guān)鍵理論與技術(shù)
- Web用戶查詢?nèi)罩就诰蚺c應(yīng)用
- 商業(yè)的本質(zhì)和互聯(lián)網(wǎng)
- Intelligent Mobile Projects with TensorFlow
- 計算機通信網(wǎng)絡(luò)安全
- 區(qū)塊鏈技術(shù)與應(yīng)用:打造分布式商業(yè)新生態(tài)
- 通信系統(tǒng)實戰(zhàn)筆記:無處不在的信號處理