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
- 1 回答
- 0 關注
- 187 瀏覽
添加回答
舉報