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

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
主站蜘蛛池模板: 九龙城区| 朝阳区| 钟山县| 惠安县| 嘉荫县| 阆中市| 东港市| 弥勒县| 临西县| 博白县| 沽源县| 成武县| 定结县| 浮山县| 丰城市| 镇坪县| 法库县| 正阳县| 石嘴山市| 永兴县| 尼玛县| 鱼台县| 若尔盖县| 富川| 运城市| 远安县| 华宁县| 丹东市| 庄河市| 迁西县| 新晃| 澄江县| 济阳县| 汶上县| 抚顺县| 博客| 宜宾市| 扶余县| 三江| 剑阁县| 东至县|