how to detect in go that connection is closed without interfering into it (reading or writing data)

67 views
Skip to first unread message

Sergey Naumov

unread,
Jan 19, 2018, 12:21:10 PM1/19/18
to golang-nuts
Hi All.

I see https://github.com/golang/go/issues/10940 issue that relates to my problem, and it looks like I must read from / write to a connetion to check whether it is alive, but want to ask if something get changed since this bug was closed without a fix.

A bit of context:

I'm dialing to remote server, then "swapping sides" and establish a gRPC listener on a client side, while remote server becomes gRPC client:

func connectAndServe(service *controlPCService) error {
        conn
, err := net.Dial("tcp", config.CloudURL)
       
if err != nil {
               
return err
       
}

        err
= conn.(*net.TCPConn).SetKeepAlive(true)
       
if err != nil {
                conn
.Close()
               
return err
       
}

        err
= conn.(*net.TCPConn).SetKeepAlivePeriod(10 * time.Second)
       
if err != nil {
                conn
.Close()
               
return err
       
}

       
var opts []grpc.ServerOption
        grpcServer
:= grpc.NewServer(opts...)

        service
.grpcServer = grpcServer
        pb
.RegisterControlPCServiceServer(grpcServer, service)
        grpcServer
.Serve(NewListener(conn)) // it blocks
       
return nil
}

NewListener(conn) just returns this connection once to gRPC server, and then blocks to emulate a situation, that there are no other connections. The problem here, is that gRPC server still thinks that it is a server => after this single connection was closed by remote side, it just waits for another one instead of exiting.

AFAIU the only thing I can do here is to listen on connection for POLLHUP or try to read 0 bytes from it until I get EOF, but as the issue 10940 says, I can't do it. Is there any means to overcome it except of implemening some kind of keepalive logic using gRPC calls?

Thanks in advance,
Sergey.
Reply all
Reply to author
Forward
0 new messages