官术网_书友最值得收藏!

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:

  1. 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()
}
  1. Run the program with the following command:
$ go run tcp-server-write-data.go
主站蜘蛛池模板: 民勤县| 武清区| 庆云县| 钟祥市| 嘉黎县| 天台县| 乃东县| 扎赉特旗| 康定县| 宁河县| 竹溪县| 大化| 渑池县| 麦盖提县| 宜良县| 顺平县| 谷城县| 黄梅县| 西城区| 汉阴县| 文化| 冷水江市| 竹山县| 庆元县| 南昌市| 茌平县| 海阳市| 调兵山市| 都昌县| 大余县| 固安县| 息烽县| 宁德市| 鲁山县| 华坪县| 阳江市| 富阳市| 南投县| 余庆县| 曲沃县| 桓台县|