tarm / serial

BSD 3-Clause "New" or "Revised" License
1.6k stars 453 forks source link

when read 0 bytes not return EOF on windows #43

Open xjiaj8 opened 8 years ago

xjiaj8 commented 8 years ago

c := &serial.Config{Name: "COM4", Baud: 115200, ReadTimeout: time.Second * 5} conn,_:=serial.OpenPort(c) buf:= bytes.NewBufferString("")

n, err := buf.ReadFrom(conn) //always block!! fmt.Printf("% x,%d,%v\n",buf.Bytes(),n,err) buf.Reset()

tarm commented 8 years ago

Unfortunately I don't have a windows computer to test with right now. What do you see when you run that code? What do you see if you do

buf := make([]byte, 1<<10) n, err := conn.Read(buf) fmt.Println("% x,%d,%v\n",buf[:n],n,err)

I'm not sure that the package has documented and committed to a particular return code (EOF or something with a .Timeout() method) after a timeout.

The recommended way is to just use a plain []byte slice and call c.Read() directly.

ohac commented 7 years ago

conn.Read(buf) returns 0 and nil when timeout.

io.Reader:

Implementations of Read are discouraged from returning a zero byte count with a nil error, except when len(p) == 0.

bufio.ReadFrom implementation is:

https://golang.org/src/bufio/bufio.go?s=16790:16849#L672

I think a zero byte with a nil error causes infinite loop.

typecampo commented 6 years ago

time.Millisecond works for me on Windows 8.1

ReadTimeout: time.Millisecond * 5000