1 回答

TA貢獻1883條經(jīng)驗 獲得超3個贊
應(yīng)用程序?qū)?shù)據(jù)發(fā)送到緩沖的讀取器,然后丟棄讀取器和它可能緩沖超過第一行的任何數(shù)據(jù)。
在連接的生命周期內(nèi)保留緩沖的閱讀器:
rdr := bufio.NewReader(conClient)
for {
netData, err := rdr.ReadString('\n')
...
您可以通過消除 goroutine 來簡化代碼(并修復(fù)與緩沖區(qū)問題無關(guān)的其他問題)。使用讀取期限來處理無響應(yīng)的服務(wù)器。
func HandleClientConnection(conClient net.Conn) {
defer conClient.Close()
chnLogging <- "Connection from " + conClient.RemoteAddr().String()
conClient.SetReadDeadline(time.Minute * SERVER_INACTIVITY_TIMEOUT_MINUTES)
scanner := bufio.NewScanner(conClient)
for scanner.Scan() {
var strctNetEncrypted stctNetEncrypted
err := json.Unmarshal(scanner.Bytes(), &strctNetEncrypted)
CheckErr(err)
switch strctNetEncrypted.IntMode {
// Insert contents of switch statement from
// question here with references to
// chnCloseConn removed.
}
conClient.SetReadDeadline(time.Minute * SERVER_INACTIVITY_TIMEOUT_MINUTES)
}
if scanner.Err() != nil {
chnLogging <- "Error from client " + conClient.RemoteAddr().String() + ": " + err.Error()
} else {
chnLogging <- "Client " + conClient.RemoteAddr().String() + " disconnected"
}
}
- 1 回答
- 0 關(guān)注
- 121 瀏覽
添加回答
舉報