Go net包中TCPConn用来建立TCP客户端、TCP服务器端间的通信通道。类似于Python中的socket对象(通过socket.socket创建)通过DialTCP函数创建该对象。TCPListener服务器端socket,监听网络请求,通过ListenTCP函数创建该对象。形象地理解,可以把TCPConn看作是TCP的连接器;TCPListener看作是TCP监听器。监听器等待客户端连接,一旦有连接进来,创建TCP连接器,然后通过TCP连接器进行服务器端和客户端的通信。
for { conn, err := listener.AcceptTCP() if err != nil { log.Fatal(err) // 错误直接退出 }
fmt.Println("remote address:", conn.RemoteAddr()) go echo(conn) } }
通过终端直接启动。
1
go run tcp_tick_time.go
通过简单的客户端连接,我们可以看到该程序终端的显示信息:
1 2 3 4 5 6 7 8 9 10 11
remote address: 127.0.0.1:1915 send 37 bytes to 127.0.0.1:1915 send 37 bytes to 127.0.0.1:1915 send 37 bytes to 127.0.0.1:1915 send 35 bytes to 127.0.0.1:1915 send 37 bytes to 127.0.0.1:1915 send 37 bytes to 127.0.0.1:1915 send 37 bytes to 127.0.0.1:1915 2017/08/29 9:23:49 write tcp4 127.0.0.1:8000->127.0.0.1:1915: wsasend: An established connection was aborted by the software in your host machine. send 0 bytes to 127.0.0.1:1915