- 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
推薦閱讀
- 物聯網與北斗應用
- Learning Karaf Cellar
- 數字通信同步技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- 2018網信發展報告
- 企業網絡安全管理
- 電力物聯網工程技術原理與應用
- 通信原理及MATLAB/Simulink仿真
- OMNeT++與網絡仿真
- Windows Server 2012 Hyper-V虛擬化管理實踐
- 工業互聯網創新實踐
- 互聯網+思維與創新:通往未來的+號
- 網絡工程實施技術與方案大全
- 深入理解Nginx:模塊開發與架構解析
- Microsoft Power Platform Enterprise Architecture
- INSTANT LinkedIn Customization How-to