43 lines
677 B
Go
43 lines
677 B
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"log"
|
|
"net"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
//TCP client端
|
|
|
|
func main() {
|
|
|
|
//1.与server端建立链接
|
|
conn, err := net.Dial("tcp", "127.0.0.1:20000")
|
|
if err != nil {
|
|
log.Fatal("dial server failed on:", err)
|
|
}
|
|
defer conn.Close()
|
|
//2.发送数据
|
|
reader := bufio.NewReader(os.Stdin)
|
|
buf := make([]byte, 1024)
|
|
for {
|
|
fmt.Print("请发送信息:")
|
|
msg, _ := reader.ReadString('\n')
|
|
msg = strings.TrimSpace(msg)
|
|
if msg == "exit" {
|
|
break
|
|
}
|
|
conn.Write([]byte(msg))
|
|
fmt.Println("等待回复中..")
|
|
n, err := conn.Read(buf)
|
|
if err != nil {
|
|
log.Fatal("读取信息失败", err)
|
|
}
|
|
fmt.Println(string(buf[:n]))
|
|
|
|
}
|
|
|
|
}
|