I have some problem with a TCP connection.
I have a server written in go which listen tcp connection on some port. And I have client written in Java for Android. Client establish connection with server, and then exchange some data both without any laws.
When Android changes the network type, for example from mobile network to wifi. Connection is broken, but server don't know about this problem, and think that client all ready to take a some data.
I need to detect this problem on my server so quick as possible. Ideally immediately
First I used in go SetKeepAlive(true)
and SetKeepAlivePeriod(10 * time.Second)
. It's worked, but not quickly as I need. Because go SetKeepAlivePeriod, set tcp keepalive time(idle) and tcp keepalive interval to same. For example in linux tcp keepalive retry=8, then problem with connection detected after (10 + 8*10) = 90sec = 1 min 30sec. It is very very slow :(. How to set idle and interval manual ? I watching this lib https://github.com/felixge/tcpkeepalive, but I don't trust this lib, because, in this lib socket fd copying without clear.
I can set SetKeepAlivePeriod(1 * time.Second)
, but whats about performance ? In my case, connection may be a heavily loaded or idle.
Then, i think about SetWriteDeadline. It's very useful for me, because i don't know when i receive message from client, but i know when i send message to client. But when i used SetWriteDeadline, is not working. For example
var request *http.Request
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
err := request.Write(conn)
if err != nil {
if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
log.Println("Connection WriteDeadline timeout")
}
conn.Close();
} else {
conn.SetWriteDeadline(time.Time{})
}
When after connection broken on client, I Write some data into connection, method Write return nil without error. As though data already send and server success accepted ACK from client, but how ?
Update 28.10.2015 22:35
I decided to try this https://github.com/felixge/tcpkeepalive library. And yet it works perfectly for my problem :).
ka, _ := tcpkeepalive.EnableKeepAlive(conn)
ka.SetKeepAliveCount(2)
ka.SetKeepAliveInterval(3 * time.Second)
ka.SetKeepAliveIdle(10 * time.Second)