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

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
主站蜘蛛池模板: 通江县| 馆陶县| 上饶县| 安吉县| 五华县| 六盘水市| 穆棱市| 阳江市| 龙陵县| 灵寿县| 宝山区| 铁岭县| 颍上县| 兰考县| 咸丰县| 东方市| 衡山县| 汝南县| 岳西县| 绍兴市| 平山县| 前郭尔| 东城区| 湘西| 砚山县| 武隆县| 新竹市| 东城区| 沐川县| 都昌县| 页游| 三台县| 五河县| 兴隆县| 天峨县| 株洲市| 石家庄市| 大理市| 文水县| 和顺县| 安溪县|