Go程序网络编程案例--计算时差

这是TCP服务器和客户端程序,实现客户端发送时间戳,服务器接受时计算上自己的时间戳,然后计算时延。

服务器代码:
package main
import (
"bufio"
"fmt"
"net"
"time"
//"strconv"
//"strings"
//"strings"
)
const (
// See http://golang.org/pkg/time/#Parse
timeFormat = "2006-01-02 15:04:05.00000000"
)

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("From client's msg:"+string(message))
clientTimeStampStr := stringToTime(message)

    serverTimeStampStr := stringToTime(time.Now().String())
    fmt.Println("Client TimeStamp:"+clientTimeStampStr)
    fmt.Println("Server TimeStamp:"+serverTimeStampStr)

    clientTimeStamp, err := time.Parse(timeFormat, clientTimeStampStr)
    if err != nil {
        fmt.Println(err)
    }

    serverTimeStamp, err := time.Parse(timeFormat, serverTimeStampStr)
    if err != nil {
        fmt.Println(err)
    }


    gap := serverTimeStamp.Sub(clientTimeStamp)
    fmt.Print("Latency:")
    fmt.Println(gap)
}

}

func stringToTime (timestr string) string {
//this is the way to get the correct time, no matter the length of time
//arrary := strings.Split(timestr," ")
//correcttimestr := arrary[0]+" "+arrary[1]

//this is the way to get the last 8 bit number
return timestr[0:28]

}

客户端代码:
package main

import (
"bufio"
"fmt"
"net"
"time"
"strconv"
)
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 func () {
fmt.Println("The client connection is close!")
conn.Close()
}()
fmt.Println("client connected!")
//go onMessageRecived(conn)
onSendMsg(conn)
//b := []byte("client time\n")
//conn.Write(b)
//<-quitSemaphore
}

func onMessageRecived(conn net.TCPConn) {
reader := bufio.NewReader(conn)
for i := 0; i < 10; i++ {
fmt.Println("This is " + strconv.Itoa(i) + " time to read")
msg, err := reader.ReadString('\n')
fmt.Println("From sever's msg:"+msg)
if err != nil {
quitSemaphore <- true
break
}
time.Sleep(1
time.Microsecond)
time.Sleep(1*time.Nanosecond)
b := []byte(msg)
conn.Write(b)

}
//quitSemaphore <- true
close(quitSemaphore)

}

func onSendMsg(conn *net.TCPConn) {
for i := 1; i <= 10; i++ {
fmt.Println("Client sending " + strconv.Itoa(i) + " packets to server")
msg := time.Now().String() + "\n"
fmt.Println("Client send msg: "+msg)
b := []byte(msg)
conn.Write(b)
}
//quitSemaphore <- true
//close(quitSemaphore)
}

计算时间的时候有很多种方法,但不用纠结于必须精确。采用简单有效的方法来节省写代码时间也是一种好方法。

推荐阅读更多精彩内容