Go語言伺服器開發之簡易TCP用戶端與服務端實現方法_Golang

來源:互聯網
上載者:User

本文執行個體講述了Go語言伺服器開發之簡易TCP用戶端與服務端實現方法。分享給大家供大家參考。具體實現方法如下:

Go語言具備強大的伺服器開發支援,這裡示範了最基礎的伺服器開發:通過TCP協議實現用戶端與伺服器的通訊。

一 服務端,為每個用戶端新開一個goroutine

複製代碼 代碼如下:
func ServerBase() { 
    fmt.Println("Starting the server...") 
    //create listener 
    listener, err := net.Listen("tcp", "192.168.1.27:50000") 
    if err != nil { 
        fmt.Println("Error listening:", err.Error()) 
        return 
    } 
 
    // listen and accept connections from clients: 
    for { 
        conn, err := listener.Accept() 
        if err != nil { 
            fmt.Println("Error accepting:", err.Error()) 
            return 
        } 
        //create a goroutine for each request. 
        go doServerStuff(conn) 
    } 

 
func doServerStuff(conn net.Conn) { 
    fmt.Println("new connection:", conn.LocalAddr()) 
    for { 
        buf := make([]byte, 1024) 
        length, err := conn.Read(buf) 
        if err != nil { 
            fmt.Println("Error reading:", err.Error()) 
            return 
        } 
 
        fmt.Println("Receive data from client:", string(buf[:length])) 
    } 
}

二 用戶端 串連伺服器,並發送資料

複製代碼 代碼如下:
func ClientBase() { 
    //open connection: 
    conn, err := net.Dial("tcp", "192.168.1.27:50000") 
    if err != nil { 
        fmt.Println("Error dial:", err.Error()) 
        return 
    } 
 
    inputReader := bufio.NewReader(os.Stdin) 
    fmt.Println("Please input your name:") 
    clientName, _ := inputReader.ReadString('\n') 
    inputClientName := strings.Trim(clientName, "\n") 
 
    //send info to server until Quit 
    for { 
        fmt.Println("What do you send to the server? Type Q to quit.") 
        content, _ := inputReader.ReadString('\n') 
        inputContent := strings.Trim(content, "\n") 
        if inputContent == "Q" { 
            return 
        } 
 
        _, err := conn.Write([]byte(inputClientName + " says " + inputContent)) 
        if err != nil { 
            fmt.Println("Error Write:", err.Error()) 
            return 
        } 
    } 
}

註:由於LiteIDE不支援同時運行多個程式,所以需要在終端通過 go run 命令來同時運行服務端和(一個或多個)用戶端,可觀察到伺服器對並發訪問的支援。

希望本文所述對大家的Go語言程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.