- 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
推薦閱讀
- 通信網(wǎng)絡(luò)基礎(chǔ)與設(shè)備
- 物聯(lián)網(wǎng)智慧安監(jiān)技術(shù)
- INSTANT PhpStorm Starter
- 5G承載網(wǎng)網(wǎng)絡(luò)規(guī)劃與組網(wǎng)設(shè)計
- 面向云平臺的物聯(lián)網(wǎng)多源異構(gòu)信息融合方法
- 計算機網(wǎng)絡(luò)工程實用教程(第2版)
- 區(qū)塊鏈輕松上手:原理、源碼、搭建與應(yīng)用
- Bonita Open Solution 5.x Essentials
- 4G小基站系統(tǒng)原理、組網(wǎng)及應(yīng)用
- 網(wǎng)絡(luò)安全應(yīng)急響應(yīng)技術(shù)實戰(zhàn)指南
- 網(wǎng)絡(luò)AI+:2030后的未來網(wǎng)絡(luò)
- 6G無線網(wǎng)絡(luò)空口關(guān)鍵技術(shù)
- Getting Started with Memcached
- 轉(zhuǎn)化:提升網(wǎng)站流量和轉(zhuǎn)化率的技巧
- Qt5 Python GUI Programming Cookbook