亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go 中的雙向連接

Go 中的雙向連接

Go
斯蒂芬大帝 2021-06-09 17:46:09
我正在嘗試在 Go 中進行簡單的控制臺聊天,只是為了練習。但是,我不知道如何從服務器發回消息。服務器只是收到一條消息,然后關閉連接。我如何發送回復?我一直在搜索并找到有關 websockets 的信息,但我認為它們用于與瀏覽器交互。這是服務器的兩個功能:func runServer() {    // Listen on a port    listen, error := net.Listen("tcp", ":8272")    // Handles eventual errors    if error != nil {        fmt.Println(error)        return    }    fmt.Println("Listening in port 8272.")    for {        // Accepts connections        con, error := listen.Accept()        // Handles eventual errors        if error != nil {            fmt.Println(error)            continue        }        fmt.Println("Connection accepted.")        // Handles the connection        go handleConnection(con)    }}func handleConnection(con net.Conn) {    fmt.Println("Handling connection.")    var message string    // Decodes the received message    decoder := gob.NewDecoder(con)    error := decoder.Decode(&message)    // Checks for errors    if error != nil {        fmt.Println(error)    } else {        fmt.Println("Received", message)    }    // Closes the connection    con.Close()    fmt.Println("Connection closed.")}這是客戶端的功能:func runClient() {    // Connects to server    con, error := net.Dial("tcp", "127.0.0.1:8272")    // Handles eventual errors    if error != nil {        fmt.Println(error)        return    }    fmt.Println("Connected to 127.0.0.1:8272.")    // Sends a message    message := "Hello world"    encoder := gob.NewEncoder(con)    error = encoder.Encode(message)    // Checks for errors    if error != nil {        fmt.Println(error)    }    con.Close()    fmt.Println("Message sent. Connection closed.")}提前致謝。
查看完整描述

1 回答

?
當年話下

TA貢獻1890條經驗 獲得超9個贊

你的con對象是一個連接,它具有Read和Write這里所描述的方法:在這里。您應該循環連接,嘗試Read傳入數據,然后處理它并(可能)Write返回服務器響應。(這里,bufferiopackage之類的可以幫你更方便的處理,這只是底層ReadWriter接口)


文檔顯示了一個小例子:


go func(c net.Conn) {

    // Echo all incoming data.

    io.Copy(c, c)

    // Shut down the connection.

    c.Close()

}(conn)

它只處理第一條消息,然后關閉。您可以像這樣處理每個傳入的消息:


go func(c net.Conn) {

    // Infinite loop: Get data, copy them and start over

    for {

        // Echo all incoming data.

        io.Copy(c, c)

    }

    // Shut down the connection.

    c.Close()

}(conn)

io.Copy當然,替換與您的服務器相關的任何內容,因此您的示例將是這樣的:


func handleConnection(con net.Conn) {

    fmt.Println("Handling connection.")


    defer func() {

        // Closes the connection

        con.Close()

        fmt.Println("Connection closed.")

    }()


    var message string


    // Decodes the received message

    decoder := gob.NewDecoder(con)

    encoder := gob.NewEncoder(con)

    for {

        error := decoder.Decode(&message)


        // Checks for errors

        if error != nil {

            fmt.Println(error)

            // Exit the loop

            return

        } else {

            fmt.Println("Received", message)

            // Sending back

            if error = encoder.Encode(message); error != nil {

                 fmt.Println(error)

                 return

            } else {

                fmt.Println("Echo'd successfuly ! Waiting for next message...")

            }

        }

    }

}

此外,您可能應該使用 packagelog而不是fmt您的日志消息(但這在這里無關緊要)。


了解這一切如何工作的一個好地方是在此處瀏覽默認http服務器的實現。


同樣,您的客戶端應該使用相同的模式循環:


LOOP:

    Send data (e.g. encoder.Encode)

    Receive data (e.g. decoder.Decode)

    if problem or termination -> break out of loop

END

close connection


查看完整回答
反對 回復 2021-06-28
  • 1 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號