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

  • Go Web Development Cookbook
  • Arpit Aggarwal
  • 155字
  • 2021-08-27 19:01:13

How to do it…

In this recipe, we are going to update the main() method to call a handleRequest method passing the connection object to read and print data on the server console. Perform the following steps:

  1. Create tcp-server-read-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 from the client: ", string(message))
conn.Close()
}
  1. Run the program with the following command:
$ go run tcp-server-read-data.go
主站蜘蛛池模板: 南郑县| 芜湖市| 平陆县| 岳阳县| 奉贤区| 安达市| 中超| 军事| 德安县| 梨树县| 元氏县| 舞阳县| 呼和浩特市| 布尔津县| 岳池县| 普兰店市| 都江堰市| 鄂尔多斯市| 茌平县| 温泉县| 胶州市| 龙陵县| 安达市| 贡觉县| 墨玉县| 澳门| 休宁县| 肇州县| 开封市| 太保市| 肥西县| 光山县| 隆子县| 绥江县| 韶关市| 陇川县| 山阳县| 班戈县| 托克逊县| 辰溪县| 德令哈市|