coder/websocket

Reader() can only read one message, but Read() can read all messages

linteck opened this issue · 5 comments

Version : nhooyr.io/websocket v1.8.10

I used this function to create a reader. But from the reader I can only read one message from server. Then I get EOF.
func (c *Conn) Reader(ctx context.Context) (MessageType, io.Reader, error)

But if I use this Read function, I can read all the messages from server.
func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error)

nhooyr commented

Can you post your code? Read uses Reader under the hood so you're likely not doing it right.

Thank you!
Here is my test case https://github.com/linteck/real-time-metrics/blob/master/backend/stream_test.go
You need clone the git repository and run test in sub directory ./backend

In this test case, the server has generated 10 messages.

go test -v -run TestParallelWebscketReader
Will only show one reply "stream_test.go:135: Get Reply: "

go test -v -run TestParallelWebscket
Will show all ten replies "stream_test.go:135: Get Reply: "

nhooyr commented

https://github.com/linteck/real-time-metrics/blob/master/backend/stream_test.go#L62

You can't call Reader once. You have to call Reader in a loop every time. One Reader call corresponds to one message. See the echo example.

https://github.com/nhooyr/websocket/blob/e3a2d32f704fb06c439e56d2a85334de04b50d32/internal/examples/echo/server.go#L40

Create Reader in the loop fixed the issue.
Thank you very much!

nhooyr commented

Awesome!