go语言网络编程通信案例
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
// 客户端
func main() {
conn, err := net.Dial("tcp", "localhost:8889")
if err != nil {
fmt.Println("客户端连接服务端错误:", err)
return
}
defer conn.Close()
for {
fmt.Println("请输入消息(输入exit退出客户端):")
// 发送消息给服务端
readString, err := bufio.NewReader(os.Stdin).ReadString('\n') // 终端接收标准输入
readString = strings.TrimSpace(readString) // 去除字符串两端的空白字符
if readString == "exit" {
break
}
if err != nil {
fmt.Println("终端读取数据失败:", err)
continue
} else {
fmt.Println("即将发送数据:", readString)
}
n, err := conn.Write([]byte(readString))
if err != nil {
fmt.Println("发送数据失败:", err)
continue
}
fmt.Println("已发送数据字节数:", n)
}
fmt.Println("成功退出客户端!!!!!!!")
}