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

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
主站蜘蛛池模板: 丽江市| 阿拉尔市| 水城县| 察雅县| 贞丰县| 周口市| 漾濞| 奇台县| 凉山| 营山县| 闽清县| 赤壁市| 常熟市| 额敏县| 塘沽区| 湘西| 安康市| 景宁| 龙井市| 绵竹市| 东乌| 滕州市| 苏尼特左旗| 阿瓦提县| 怀来县| 林甸县| 万年县| 电白县| 鸡泽县| 二手房| 铜鼓县| 沂源县| 金门县| 福建省| 通辽市| 涞源县| 阿荣旗| 射洪县| 樟树市| 维西| 沁阳市|