server1:
package main
import (
"fmt"
"net"
)
func main() {
l, err := net.Listen("tcp", "127.0.0.1:9876")
if err != nil {
fmt.Println(err)
}
fmt.Println("服务器等待客户端连接")
conn, err := l.Accept()
if err != nil {
fmt.Println(err)
}
defer conn.Close()
fmt.Println("客户端建立连接 ")
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(buf[:n]))
conn.Write(buf[:n])
}
client1:
package main
import (
"fmt"
"net"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:9876")
if err != nil {
fmt.Println(err)
}
defer conn.Close()
conn.Write([]byte("are you ready"))
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(buf[:n]))
}
有疑问加站长微信联系(非本文作者)