本节我们就从实现一个简单的echo的服务端/客户端来入手, 了解golang的实现tcp长连接服务器的具体细节.
首先, 我们先列一下服务端的实现思路及步骤:
我们可以在实验环境的主文件夹中, 建立一个名为server.go的文件, 在其中编写服务器端程序代码
服务端程序清单如下:
server.go
package main
import (
"bufio"
"fmt"
"net"
"time"
)
func main() {
var tcpAddr *net.TCPAddr
tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:9999")
tcpListener, _ := net.ListenTCP("tcp", tcpAddr)
defer tcpListener.Close()
for {
tcpConn, err := tcpListener.AcceptTCP()
if err != nil {
continue
}
fmt.Println("A client connected : " + tcpConn.RemoteAddr().String())
go tcpPipe(tcpConn)
}
}
func tcpPipe(conn *net.TCPConn) {
ipStr := conn.RemoteAddr().String()
defer func() {
fmt.Println("disconnected :" + ipStr)
conn.Close()
}()
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
return
}
fmt.Println(string(message))
msg := time.Now().String() + "\n"
b := []byte(msg)
conn.Write(b)
}
}
接着, 我们打开终端, 编译服务端程序:
go build server.go
编译成功的话, 会在主目录中看到编译成功的server程序
接下来, 是客户端的代码实现步骤:
程序清单如下:
client.go
package main
import (
"bufio"
"fmt"
"net"
"time"
)
var quitSemaphore chan bool
func main() {
var tcpAddr *net.TCPAddr
tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:9999")
conn, _ := net.DialTCP("tcp", nil, tcpAddr)
defer conn.Close()
fmt.Println("connected!")
go onMessageRecived(conn)
b := []byte("time\n")
conn.Write(b)
<-quitSemaphore
}
func onMessageRecived(conn *net.TCPConn) {
reader := bufio.NewReader(conn)
for {
msg, err := reader.ReadString('\n')
fmt.Println(msg)
if err != nil {
quitSemaphore <- true
break
}
time.Sleep(time.Second)
b := []byte(msg)
conn.Write(b)
}
}
编译客户端:
go build client.go
最后, 开启两个终端, 分别运行server和client
可以看到以下类似的输出:
connected! 2015-03-19 23:42:08.4875559 +0800 CST
2015-03-19 23:42:09.4896132 +0800 CST
2015-03-19 23:42:10.4906704 +0800 CST
2015-03-19 23:42:11.4917277 +0800 CST
2015-03-19 23:42:12.4927849 +0800 CST
2015-03-19 23:42:13.4938422 +0800 CST
2015-03-19 23:42:14.4948995 +0800 CST
2015-03-19 23:42:15.4959567 +0800 CST
2015-03-19 23:42:16.497014 +0800 CST
2015-03-19 23:42:17.4980712 +0800 CST
2015-03-19 23:42:18.4991285 +0800 CST
2015-03-19 23:42:19.5001857 +0800 CST
这样, 一个简单的echo服务器/客户端就实现了