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

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
主站蜘蛛池模板: 博白县| 赤峰市| 宜城市| 南木林县| 绩溪县| 延寿县| 武川县| 佛坪县| 乐安县| 灵璧县| 阿克| 六枝特区| 阳东县| 扎兰屯市| 阿拉善左旗| 荔浦县| 微山县| 灵寿县| 凌云县| 凤山市| 安达市| 垦利县| 哈巴河县| 泗阳县| 滁州市| 泾源县| 庆元县| 县级市| 太仓市| 凤冈县| 诸暨市| 嘉黎县| 西乌| 交口县| 西青区| 景东| 白城市| 宣城市| 宣城市| 孟州市| 广丰县|