目录
服务端操作流程
客户端操作流程
服务端代码:
客户端代码:
运行效果:
服务端操作流程
1.监听端口2.接收客户端请求建立链接3.创建goroutine处理链接。
客户端操作流程
1.建立与服务端的链接2.进行数据收发3.关闭链接
服务端代码:
package mainimport ("bufio""fmt""net"
)func process(conn net.Conn) {defer conn.Close() //关闭连接fmt.Println("connection suess!")for {reader := bufio.NewReader(conn)var buf [128]byten, err := reader.Read(buf[:]) //读取数据if err != nil {fmt.Println("read from client failed,error:", err)break} else {fmt.Println("suess read!")}recvStr := string(buf[:n])fmt.Println("收到client端发送的数据:", recvStr)// conn.Write([]byte(recvStr)) //发送数据}
}func main() {// listen, err := net.Listen("tcp", "127.0.0.1:20000")listen, err := net.Listen("tcp", "localhost:8888")if err != nil {fmt.Println("Listen failed,error:", err)return} else {fmt.Println("suess listen!")}fmt.Println("waiting for client")for {conn, err := listen.Aept() //建立连接if err != nil {fmt.Println("aept failed,error:", err)continue} else {fmt.Println("suess aept!")}go process(conn) //启动一个goroutine处理连接}
}
客户端代码:
package mainimport ("bufio""fmt""net""os""strings"
)func main() {fmt.Println("client start!\n","按下q退出……\n","输入发送的内容后按下回车键发送!\n")conn, err := net.Dial("tcp", "localhost:8888")if err != nil {fmt.Println("error:", err)return}defer conn.Close() //关闭连接inputReader := bufio.NewReader(os.Stdin)for {input, _ := inputReader.ReadString('\n') //读取用户输入inputInfo := strings.Trim(input, "\r\n")if strings.ToUpper(inputInfo) == "Q" { //输入q/Q就退出return}_, err = conn.Write([]byte(inputInfo)) // 发送数据if err != nil {return}buf := [512]byte{}n, err := conn.Read(buf[:])if err != nil {fmt.Println("recv failed,err:", err)return}fmt.Println(string(buf[:n]))}
}
运行效果: