![](/img/trans.png)
[英]bufio.NewReader ReadBytes - Reading multiple message at the same time
[英]EOF error when reading from port with bufio
我正在嘗試學習net
軟件包。 我正在偵聽端口上的本地連接,並使用echo -n "Server test.\\n" | nc localhost 5000
將數據發送到該端口echo -n "Server test.\\n" | nc localhost 5000
echo -n "Server test.\\n" | nc localhost 5000
。
但是,讀取數據時總是出現EOF
錯誤。 我檢查了文檔,僅在沒有更多輸入可用時才會發生這種情況,但是我不明白為什么在這里發生這種情況。
這是我的代碼:
package main
import (
"bufio"
"fmt"
"net"
"os"
)
// Connection details
type connection struct {
host string
port string
network string
}
// Initialise a Listener on a given port
// Pass handling into seperate goroutine
func main() {
localConn := connection{
host: "", // Localhost
port: "5000",
network: "tcp",
}
listener, err := net.Listen(localConn.network, localConn.host+":"+localConn.port)
checkError("Error listening: ", err)
conn, err := listener.Accept()
for {
checkError("Error accepting: ", err)
go handleRequest(conn)
}
}
// Delegate handling of requests
func handleRequest(conn net.Conn) {
// Read message up until newline delimiter
message, err := bufio.NewReader(conn).ReadString('\n')
checkError("Error reading: ", err)
fmt.Println("Message recieved: ", string(message))
conn.Write([]byte("Recieved message: " + string(message) + "\n"))
conn.Close()
}
// Check if an error exists
// If so, print and exit program. (Not super robust!)
func checkError(message string, err error) {
if err != nil {
fmt.Println(message, err.Error())
os.Exit(1)
}
}
這些線上的問題是:
conn, err := listener.Accept()
for {
checkError("Error accepting: ", err)
go handleRequest(conn)
}
該應用程序循環啟動goroutines以讀取單個連接。 讀取連接的第一個goroutine成功。 后續goroutines報告錯誤。
將代碼更改為:
for {
conn, err := listener.Accept()
checkError("Error accepting: ", err)
go handleRequest(conn)
}
客戶端未按服務器預期發送換行符。 使用此命令發送消息:
echo "Server test." | nc localhost 5000
您似乎錯誤地使用了echo
。 標志-e
將兩個字符\\n
解釋為換行符( 在此處檢查)。
使用以下命令將數據發送到服務器:
echo -e "Server test.\n" | nc localhost 5000
除此之外,您還應該修正for
環:
for {
conn, err := listener.Accept()
checkError("Error accepting: ", err)
go handleRequest(conn)
}
在您的原始代碼中,您僅接受一種連接。 之后,for循環僅啟動更多goroutine,嘗試在關閉的連接上讀取(無論是否出錯,第一個handleRequest
調用都會關閉連接)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.