- Go Web Development Cookbook
- Arpit Aggarwal
- 277字
- 2021-08-27 19:01:12
How it works…
Once we run the program, the TCP server will start locally listening on port 8080.
Let’s understand what each line in the program means:
- package main: This defines the package name of the program.
- import ( "log" "net"): This is a preprocessor command that tells the Go compiler to include all files from the log and net package.
- const ( CONN_HOST = "localhost" CONN_PORT = "8080" CONN_TYPE = "tcp" ): We declare constants in a Go program using the const keyword. Here, we declare three constants—one is CONN_HOST with a value of localhost, another one is CONN_PORT with a value as 8080, and lastly CONN_TYPE with a value as tcp.
Next, we declared the main() method from where the program execution begins. As this method does a lot of things, let’s understand it line by line:
- listener, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT): This creates a TCP server running on localhost at port 8080.
- if err != nil { log.Fatal("Error starting tcp server: ", err) }: Here, we check if there is any problem in starting the TCP server. If there is, then log the error and exit with a status code of 1.
- defer listener.Close(): This defer statement closes a TCP socket listener when the application closes.
Next, we accept the incoming request to the TCP server in a constant loop, and if there are any errors in accepting the request, then we log it and exit; otherwise, we simply print the connection object on the server console, as follows:
for
{
conn, err := listener.Accept()
if err != nil
{
log.Fatal("Error accepting: ", err.Error())
}
log.Println(conn)
}
推薦閱讀
- 物聯(lián)網(wǎng)安全(原書(shū)第2版)
- 物聯(lián)網(wǎng)(IoT)基礎(chǔ):網(wǎng)絡(luò)技術(shù)+協(xié)議+用例
- 工業(yè)控制網(wǎng)絡(luò)安全技術(shù)與實(shí)踐
- 萬(wàn)物互聯(lián):蜂窩物聯(lián)網(wǎng)組網(wǎng)技術(shù)詳解
- TCP/IP入門(mén)經(jīng)典(第5版)
- 中小型局域網(wǎng)組建、管理與維護(hù)實(shí)戰(zhàn)
- 城市治理一網(wǎng)統(tǒng)管
- 圖解手機(jī)元器件維修技巧
- Microservice Patterns and Best Practices
- Getting Started with Memcached
- 互聯(lián)網(wǎng)安全的40個(gè)智慧洞見(jiàn)(2016)
- 中國(guó)互聯(lián)網(wǎng)發(fā)展報(bào)告2021
- Building RESTful Web Services with .NET Core
- 信息技術(shù)安全評(píng)估準(zhǔn)則:源流、方法與實(shí)踐
- 物聯(lián)網(wǎng)M2M開(kāi)發(fā)技術(shù):基于無(wú)線CPU-Q26XX