server端代碼:
package main
import (
"fmt"
"net"
"log"
"os"
)
func main() {
addr := "0.0.0.0:8787"
tcpAddr, err := net.ResolveTCPAddr("tcp",addr)
if err != nil {
log.Fatalf("net.ResovleTCPAddr fail:%s", addr) //等價于print err后,再os.Exit(1)
}
listener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
log.Fatalf("listen %s fail: %s", addr, err)
}else {
log.Println("rpc listening", addr)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Println("listener.Accept error:", err)
continue
}
go handle_Client(conn)
}
}
func handle_Client(conn net.Conn) {
defer conn.Close()
var write_buffer []byte = []byte("ok")
read_buffer := make([]byte, 128)
n, err1 := conn.Read(read_buffer)
if err1 != nil {
fmt.Println("ser Read failed:", err1)
os.Exit(1)
}
m, err2 := conn.Write(write_buffer)
if err2 != nil {
fmt.Println("ser send error:", err2)
os.Exit(1)
}
fmt.Println("ser read cli send data count:", n, "msg:", string(read_buffer))
fmt.Println("ser send data to cli count:", m, "msg:", string(write_buffer))
fmt.Println("********one connetion end*********")
}
client端代碼:
package main
import (
"fmt"
"net"
"os"
"time"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:8787")
if err != nil {
fmt.Println("dial failed:", err)
os.Exit(1)
}
defer conn.Close()
var write_buffer []byte = []byte("Hi,server. I'm client.")
read_buffer := make([]byte, 128)
start_time := time.Now()
n, err2 := conn.Write(write_buffer)
if err2 != nil {
fmt.Println("cli send error:", err2)
os.Exit(1)
}
m, err1 := conn.Read(read_buffer)
if err1 != nil {
fmt.Println("cli Read failed:", err1)
os.Exit(1)
}
response_time := time.Since(start_time)
RTT_time := float64(response_time.Nanoseconds()) / 1e+06 //ns-->ms
fmt.Println(RTT_time)
fmt.Println("cli send data to ser count:", n, "msg:", string(write_buffer))
fmt.Println("cli read ser data count:", m, "msg:", string(read_buffer))
}
補充:go 語言 TCP服務器接受客戶端字符串信息
我就廢話不多說了,大家還是直接看代碼吧~
func hand_conn(conn net.Conn) ([]byte){
defer conn.Close()
//clientarr := conn.RemoteAddr() //獲取連接到的對像的IP地址
result := bytes.NewBuffer(nil)
var buf [512]byte
for {
n, err := conn.Read(buf[0:])
result.Write(buf[0:n])
if err != nil {
if err == io.EOF {
break
}
}
}
//explan_rec_infos(string(result.Bytes()))
return result.Bytes()
}
func main() {
fmt.Println("Hello World! go server")
server, err := net.Listen("tcp", ":9993")
if err == nil { //若果err為nil,則成功創(chuàng)建
index := 1
for {
index++
con, _ := server.Accept()
fmt.Println("有一個客戶連接" , index)
hand_conn(con)
}
} else {
return
}
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- golang在GRPC中設置client的超時時間
- 解決golang時間字符串轉(zhuǎn)time.Time的坑
- golang時間處理工具箱now的使用詳解
- golang time包做時間轉(zhuǎn)換操作
- golang時間字符串和時間戳轉(zhuǎn)換的案例
- golang 實現(xiàn)時間戳和時間的轉(zhuǎn)化