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

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
主站蜘蛛池模板: 汝阳县| 南汇区| 大埔县| 昭通市| 牟定县| 偏关县| 宣化县| 阳谷县| 砀山县| 雷山县| 驻马店市| 济阳县| 汤原县| 广德县| 宝山区| 外汇| 罗山县| 阜平县| 屏东市| 都江堰市| 清苑县| 松溪县| 行唐县| 宁陵县| 涞水县| 龙游县| 乃东县| 平陆县| 抚顺市| 永城市| 张家界市| 禹州市| 祁东县| 崇礼县| 应用必备| 阿鲁科尔沁旗| 昌平区| 讷河市| 张家界市| 仪陇县| 贵定县|