golang学习笔记之tcp简单实现:server端与client端
server端
main.go
package main import ( "fmt" "net" ) func main() { // simple tcp server //1.listen ip+port listener, err := net.Listen("tcp", "0.0.0.0:9090") if err != nil { fmt.Printf("listen fail, err: %v\n", err) return } //2.accept client request //3.create goroutine for each request for { conn, err := listener.Accept() if err != nil { fmt.Printf("accept fail, err: %v\n", err) continue } //create goroutine for each connect go process(conn) } } func process(conn net.Conn) { defer conn.Close() for { var buf [128]byte n, err := conn.Read(buf[:]) if err != nil { fmt.Printf("read from connect failed, err: %v\n", err) break } str := string(buf[:n]) fmt.Printf("receive from client, data: %v\n", str) } }
client端
main.go
package main import ( "bufio" "fmt" "net" "os" "strings" ) func main() { conn, err := net.Dial("tcp", "localhost:9090") defer conn.Close() if err != nil { fmt.Printf("connect failed, err : %v\n", err.Error()) return } inputReader := bufio.NewReader(os.Stdin) for { input, err := inputReader.ReadString('\n') if err != nil { fmt.Printf("read from console failed, err: %v\n", err) break } trimmedInput := strings.TrimSpace(input) if trimmedInput == "Q" { break } _, err = conn.Write([]byte(trimmedInput)) if err != nil { fmt.Printf("write failed , err : %v\n", err) break } } }
分别编译执行服务端和客户端
客户端通过命令行与服务端简单交互