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

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
主站蜘蛛池模板: 徐闻县| 新安县| 金寨县| 贵南县| 来安县| 内江市| 墨竹工卡县| 三亚市| 屯留县| 彭水| 唐海县| 徐水县| 北川| 胶南市| 万年县| 华坪县| 五河县| 阳曲县| 边坝县| 兴宁市| 周宁县| 龙胜| 古丈县| 南溪县| 宁津县| 买车| 凌云县| 西盟| 南昌县| 北流市| 喀喇| 江安县| 西吉县| 老河口市| 客服| 东至县| 洞口县| 芮城县| 韩城市| 罗源县| 胶南市|