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

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
主站蜘蛛池模板: 金湖县| 兰州市| 循化| 滁州市| 东阿县| 讷河市| 天津市| 沂源县| 仪陇县| 贵阳市| 山东| 新兴县| 汉寿县| 新巴尔虎右旗| 上饶县| 黔南| 桃源县| 雅江县| 民丰县| 蓬莱市| 齐河县| 锦屏县| 青铜峡市| 永泰县| 灵璧县| 扬州市| 壤塘县| 宜君县| 大兴区| 泰顺县| 封丘县| 乐山市| 石阡县| 筠连县| 曲阜市| 酒泉市| 北辰区| 榕江县| 绩溪县| 行唐县| 天柱县|