import ”net“
TCP服务端
listen, err := net.Listen("tcp", "127.0.0.1:9001")
if err != nil {
log.Fatalf("Listen failed %s", err.Error())
return
}
for {
conn, err := listen.Accept()
if err != nil {
log.Fatalf("Accept Failed %s", err.Error())
}
go process(conn)
}
func process(conn net.Conn) {
defer func(conn net.Conn) {
_ = conn.Close()
}(conn) // 关闭连接
for {
var buf [128]byte // 创建缓冲区
reader := bufio.NewReader(conn)
n, err := reader.Read(buf[:])
// 判断客户端连接是否关闭
if err == io.EOF {
fmt.Println("客户端连接已关闭")
break
}
if err != nil {
log.Printf("read from client faild , %s\n", err.Error())
break
}
recvStr := string(buf[:n])
fmt.Printf("接受到客户端发送的数据: %s", recvStr)
_, _ = conn.Write([]byte(recvStr))
}
}
TCP客户端
conn,err := net.Dial("tcp","127.0.0.1:9001")
if err != nil {
fmt.Printf("connection diald error : %s\n",err.Error())
return
}
defer conn.Close()
num,err := conn.Write([]byte("hello"))
if err != nil {
fmt.Printf("write error : %s\n",err.Error())
return
}
fmt.Printf("write num : %d\n",num)
buf := make([]byte, 1024)
for {
if _, err := conn.Read(buf); err != nil {
if err == io.EOF {
fmt.Println("服务器连接断开")
return
} else {
fmt.Printf("error : %s \n", err.Error())
return
}
}
fmt.Printf("server reply : %s\n", string(buf))
}