//server端
<pre name="code" class="cpp">package main
import (
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
//"io/ioutil"
)
func main() {
service := "localhost:7777"
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
for {
conn, err := listener.Accept()
if err != nil {
continue
}
go handleClient(conn)
}
}
func handleClient(conn net.Conn) {
//设置了超时,当一定时间内客户端无请求发送,conn便会自动关闭,下面的for循环即会因为连接已关闭而跳出(即socket断开)
conn.SetReadDeadline(time.Now().Add(3 * time.Second)) // set 2 minutes timeout
request := make([]byte, 128) // set maxium request length to 128B to prevent flood attack
defer conn.Close() // close connection before exit
for {
read_len, err := conn.Read(request)
fmt.Println("------")
a := len(request)
fmt.Println(string(request))
fmt.Println(a)
fmt.Println("******")
fmt.Println(string(request[:read_len]))
fmt.Println(read_len)
if err != nil {
fmt.Println(err)
break
}
if read_len == 0 {
break // connection already closed by client
} else if strings.TrimSpace(string(request[:read_len])) == "timestamp" {
daytime := strconv.FormatInt(time.Now().Unix(), 10)
conn.Write([]byte(daytime))
} else {
daytime := time.Now().String()
conn.Write([]byte(daytime))
}
request = make([]byte, 128) // clear last read content
}
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
//client端
<pre name="code" class="cpp">package main
import (
"fmt"
"io/ioutil"
"net"
"os"
)
func main() {
service := "localhost:7777"
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkError(err)
conn, err := net.DialTCP("tcp", nil, tcpAddr)
checkError(err)
_, err = conn.Write([]byte("hello"))
checkError(err)
//注意ioutil.ReadAll和conn.Read
//区别参考http://www.golangtc.com/t/53b7a47d320b522f430000b2
result, err := ioutil.ReadAll(conn)
//request := make([]byte, 128)
//read_len, err := conn.Read(request)
checkError(err)
//fmt.Println(string(request[:read_len]))
//conn.Close()
fmt.Println(string(result))
os.Exit(0)
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
[gfj@kfjk2 bin]$ ./tcp_server
------
hello
128
******
hello
5
------
128
******
0
read tcp 127.0.0.1:7777->127.0.0.1:31020: i/o timeout
[gfj@kfjk2 bin]$ ./tcp_client
2016-08-11 21:30:19.799264092 +0800 CST