server.go
package main
import (
"fmt"
"net"
)
func process(conn net.Conn) {
defer conn.Close()
for {
buf := make([]byte, 1024)
fmt.Println("服务器在等待客户端发送信息"+conn.RemoteAddr().String())
n, err := conn.Read(buf)
if err != nil {
fmt.Printf("服务器端read error =", err)
return
}
// 显示客户端发送的内容到服务器的终端
fmt.Print(string(buf[:n]))
}
}
func main() {
listen, err := net.Listen("tcp","0.0.0.0:8888")
if err != nil {
fmt.Println("listen err = ", err)
}
// 延时关闭
defer listen.Close()
for {
// 等待客户端连接
fmt.Println("等待客户端来连接")
con, err := listen.Accept()
if err != nil {
fmt.Println("connect err = ", err)
}
fmt.Printf("connect success %v, 客户端IP = %v", con, con.RemoteAddr().String())
go process(con)
}
fmt.Printf("listen = %v", listen)
}
client.go
package main
import (
"bufio"
"fmt"
"net"
"os"
)
func main() {
conn, err := net.Dial("tcp", "0.0.0.0:8888")
if err != nil {
fmt.Println("client dial err = ", err)
return
}
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadString('\n')
if err != nil {
fmt.Println("read string err=", err)
}
n , err := conn.Write([]byte(line))
if err != nil {
fmt.Println("connect write = ", err)
}
fmt.Println("客户端发送了%d的字节, 并退出", n)
}