乐趣区

关于go:Go-TCPCS-模型

创立工程文件

mkdir tcpServer tcpClient
cd tcpServer && go mod init tcpServer && touch server.go
cd ../tcpClient && go mod init tcpClient && touch client.go

服务端

// server.go
package main

import(
    "net"
    "fmt"
    "bufio"
)


func main(){

    // get listener
    listener, err := net.Listen("tcp", ":8080")
    if err != nil{fmt.Println("listen failed:")
        panic(err)
    }
    fmt.Println("tcp server running at 127.0.0.1:8080...")
    for {
        // get connection
        conn, err := listener.Accept()
        if err != nil{fmt.Println("accept failed:")
            panic(err)
        }

        process(conn)
    }
}

func process(conn net.Conn){defer conn.Close()

    for {reader := bufio.NewReader(conn)
        var buf [128]byte
        n, err := reader.Read(buf[:])
        if err != nil{fmt.Println("read from client failed:")
            panic(err)
        }

        recvStr := string(buf[:n])
        fmt.Println("receive from client:", recvStr)

        conn.Write([]byte(recvStr + "from server"))
    }
}
$ go run server.go 
tcp server running at 127.0.0.1:8080...

客户端

// client.go
package main

import(
    "os"
    "fmt"
    "net"
    "bufio"
    "strings"
)

func main(){
    // create conn to server :8080
    conn, err := net.Dial("tcp", ":8080")
    if err != nil{fmt.Println("connnect to server failed:")
        panic(err)
    }
    defer conn.Close()

    inputReader := bufio.NewReader(os.Stdin)
    for {input, _ := inputReader.ReadString('\n')
        input_data := strings.Trim(input, "\r\n")
        if strings.ToUpper(input_data) == "Q"{return}
        // send data to server
        _, err := conn.Write([]byte(input_data))
        
        if err != nil{fmt.Println("send data to server failed:", err)
            return
        }

        // receive data from server
        buf := [512]byte{}
        n, err := conn.Read(buf[:])
        if err != nil{fmt.Println("receive data from server failed:", err)
            return
        }
        fmt.Println(string(buf[:n]))
    }
}
$ go run client.go
connect to tcp server 0.0.0.0:8080...

测试

$ go run client.go
connect to tcp server 0.0.0.0:8080...
ping
ping from server
yes
yes from server
ok
ok from server
$ go run server.go
tcp server running at 127.0.0.1:8080...
receive from client:  ping
receive from client:  yes
receive from client:  ok
退出移动版