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

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)
}
主站蜘蛛池模板: 大关县| 两当县| 张家港市| 尖扎县| 苗栗市| 巴东县| 尼勒克县| 高陵县| 石嘴山市| 泾川县| 历史| 梨树县| 湛江市| 尉氏县| 崇义县| 六安市| 五大连池市| 四川省| 永济市| 寿光市| 离岛区| 武平县| 夹江县| 寿光市| 邮箱| 渝北区| 德州市| 大名县| 定陶县| 红安县| 宾川县| 定州市| 安图县| 英吉沙县| 长宁区| 新化县| 唐河县| 兖州市| 正镶白旗| 赤城县| 甘谷县|