Server
package main
import (
"fmt"
"net"
)
func main() {
// 1.创建监听
ip := "127.0.0.1"
port := 8080
address := fmt.Sprintf("%s:%d", ip, port)
server, err := net.Listen("tcp", address)
defer server.Close()
if err != nil {
fmt.Println("net.Listen err", err)
return
}
fmt.Println("Listening...", "tcp", address)
for {
// 2.接收连接
conn, err := server.Accept()
if err != nil {
fmt.Println("server.Accept err", err)
return
}
go func() {
// 3.读取数据
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("conn.Read err", err)
return
}
fmt.Println("Clinet ====> Server ", "len:", n, " 数据:", string(buf))
// 4.给客户端发送数据
data := "Server Ok"
n, err = conn.Write([]byte(data))
fmt.Println("Server ====> Client", "len:", n, " 数据:", data)
}()
}
}
Client
package main
import (
"fmt"
"net"
"strconv"
"time"
)
func main() {
count := 0
for {
count += 1
// 1.建立连接
conn, err := net.Dial("tcp", ":8080")
if err != nil {
fmt.Println("conn err", err)
return
}
defer conn.Close()
time.Sleep(1 * time.Second)
// 2.发送数据
data := "Hello Server" + strconv.Itoa(count)
n, err := conn.Write([]byte(data))
fmt.Println("Clinet ====> Server", "len:", n, " 数据:", data)
// 3.接收数据
buf := make([]byte, 1024)
n, err = conn.Read(buf)
if err != nil {
fmt.Println("conn.Read err", err)
return
}
fmt.Println("Server ====> Clinet", "len:", n, " 数据:", string(buf))
}
}