Golang Socket 程式設計例項
阿新 • • 發佈:2018-11-12
服務端程式:
package main import ( "net" "fmt" "strings" ) func handle(conn net.Conn) { defer conn.Close() buf := make([]byte, 2048) for { n, err := conn.Read(buf) if err != nil { fmt.Println("read err = ", err) return } content := strings.TrimSpace(string(buf[:n])) fmt.Println("receive =", content) if content == "exit" { return } conn.Write([]byte(strings.ToUpper(content))) } } func main() { ss, err := net.Listen("tcp", "127.0.0.1:8000") if err != nil { fmt.Println("listen err = ", err) return } fmt.Println("listening at 127.0.0.1:8000") for { conn, err := ss.Accept() if err != nil { fmt.Println("connect err = ", err) return } go handle(conn) } }
客戶端程式:
package main import ( "net" "fmt" "os" ) func ScanLine() string { var c byte var err error var b []byte for ; err == nil; { _, err = fmt.Scanf("%c", &c) if c != '\n' { b = append(b, c) } else { break; } } return string(b) } func main() { conn, err := net.Dial("tcp", "127.0.0.1:8000") if err != nil { fmt.Println("connect err = ", err) return } go func(conn net.Conn) { buf := make([]byte, 2048) for { n, err := conn.Read(buf) if err != nil { fmt.Println("read err = ", err) return } fmt.Println(string(buf[:n])) } }(conn) for { input := ScanLine() conn.Write([]byte(input)) if input == "exit" { os.Exit(0) } } }
注意事項:
1. 從鍵盤輸入一行需要特別處理,否則可能出現一行輸入資料被分為幾段分別傳送的情況
2. 注意客戶端需新建協程處理從服務端接收的資料,主程處理鍵盤輸入