Jak sprawdzić, czy połączenie TCP jest zamknięte w pakiecie Golang net?
Jestem nowy w Golang.
Wdrażam mały serwer TCP i skąd mam wiedzieć, czy jeden z moich klientów się zamknął? Czy powinienem po prostu spróbować czytać lub pisać i sprawdzić, czy błąd jest zerowy?
42
Author: liuyanghejerry, 2012-10-05
3 answers
Ten wątek " najlepszy sposób na niezawodne wykrycie, że połączenie TCP jest zamknięte ", używając net.Conn
dla "c
" (również w utils/ping.go
lub locale-backend/server.go
lub wiele innych przypadków):
one := []byte{}
c.SetReadDeadline(time.Now())
if _, err := c.Read(one); err == io.EOF {
l.Printf(logger.LevelDebug, "%s detected closed LAN connection", id)
c.Close()
c = nil
} else {
var zero time.Time
c.SetReadDeadline(time.Now().Add(10 * time.Millisecond))
}
Do wykrywania limitu czasu sugeruje:
if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
...
50
Author: VonC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-15 18:01:49
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-15 18:01:49
Po prostu spróbuj odczytać z niego, a wyrzuci błąd, jeśli jest zamknięty. Obchodź się z gracją, jeśli chcesz!
Za ryzyko oddania zbyt wiele:
func Read(c *net.Conn, buffer []byte) bool {
bytesRead, err := c.Read(buffer)
if err != nil {
c.Close()
log.Println(err)
return false
}
log.Println("Read ", bytesRead, " bytes")
return true
}
Oto miłe wprowadzenie do używania pakietu net do tworzenia małego TCP "serwera czatu":
13
Author: minikomi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-29 04:46:43
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-29 04:46:43
_, err := conn.Read(make([]byte, 0))
if err!=io.EOF{
// this connection is invalid
logger.W("conn closed....",err)
}else{
byt, _:= ioutil.ReadAll(conn);
}
-2
Author: liam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-17 08:58:19
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-17 08:58:19