Check if net.Conn is functional without reading

I’m working with a server library that reads from a socket and routes data to user’s handler. In addition to the data it passes net.Conn (tls.Conn or net.TCPConn).

Given the net.Conn object can I, an end user, figure out in a portable way whether the connection is still functional without non-zero reading? It’s safe to assume that the server is continuously reading and will eventually encounter EOF.

At least on Darwin a zero read from a closed tls.Conn does not reveal EOF even if there was a preceding non-zero read that encountered the problem:

package main

import (
	"crypto/tls"
	"fmt"
)

func main() {
	conn, err := tls.Dial("tcp", "127.0.0.1:8853", &tls.Config{
		InsecureSkipVerify: true,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	conn.Close()
	i, err := conn.Read(make([]byte, 1))
	fmt.Println(i, err) // 0 read tcp 127.0.0.1:60604->127.0.0.1:8853: use of closed network connection
	i, err = conn.Read(make([]byte, 0))
	fmt.Println(i, err) // 0 <nil>
}

So I suppose it’s a no go. Is there anything else that can be done without mutating socket’s state? Polling for some property is fine in my use-case.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.