- 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:
- 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()
}
- Run the program with the following command:
$ go run tcp-server-read-data.go
推薦閱讀
- Cisco OSPF命令與配置手冊(cè)
- MERN Quick Start Guide
- 物聯(lián)網(wǎng)之魂:物聯(lián)網(wǎng)協(xié)議與物聯(lián)網(wǎng)操作系統(tǒng)
- 網(wǎng)絡(luò)創(chuàng)新指數(shù)研究
- WordPress 5 Complete
- 信息通信網(wǎng)絡(luò)建設(shè)安全管理概要2
- 面向物聯(lián)網(wǎng)的嵌入式系統(tǒng)開(kāi)發(fā):基于CC2530和STM32微處理器
- 中小型局域網(wǎng)組建、管理與維護(hù)實(shí)戰(zhàn)
- 城域網(wǎng)與廣域網(wǎng)(第2版)
- Bonita Open Solution 5.x Essentials
- 夢(mèng)工廠之材質(zhì)N次方:Maya材質(zhì)手冊(cè)
- 現(xiàn)代通信系統(tǒng)(第5版)
- 互聯(lián)網(wǎng)安全的40個(gè)智慧洞見(jiàn)(2016)
- 基于IPv6的家居物聯(lián)網(wǎng)開(kāi)發(fā)與應(yīng)用技術(shù)
- Selenium WebDriver 3 Practical Guide