Browse Source

fix review and tests

pull/1422/head
Jeromy 7 years ago
parent
commit
cb1cddaeb6
  1. 38
      p2p/transport/websocket/conn.go
  2. 11
      p2p/transport/websocket/websocket_test.go

38
p2p/transport/websocket/conn.go

@ -25,25 +25,42 @@ func (c *Conn) Read(b []byte) (int, error) {
}
}
n, err := c.reader.Read(b)
if err == io.EOF {
if err := c.prepNextReader(); err != nil {
return 0, err
}
if n == 0 {
n, err = c.reader.Read(b)
for {
n, err := c.reader.Read(b)
switch err {
case io.EOF:
c.reader = nil
if n > 0 {
return n, nil
}
if err := c.prepNextReader(); err != nil {
return 0, err
}
// explicitly looping
default:
return n, err
}
}
return n, err
}
func (c *Conn) prepNextReader() error {
_, r, err := c.Conn.NextReader()
t, r, err := c.Conn.NextReader()
if err != nil {
if wserr, ok := err.(*ws.CloseError); ok {
if wserr.Code == 1000 || wserr.Code == 1005 {
return io.EOF
}
}
return err
}
if t == ws.CloseMessage {
return io.EOF
}
c.reader = r
return nil
}
@ -61,6 +78,7 @@ func (c *Conn) Close() error {
c.done()
}
c.Conn.WriteMessage(ws.CloseMessage, nil)
return c.Conn.Close()
}

11
p2p/transport/websocket/websocket_test.go

@ -2,7 +2,9 @@ package websocket
import (
"bytes"
"io/ioutil"
"testing"
"testing/iotest"
ma "github.com/multiformats/go-multiaddr"
)
@ -40,13 +42,14 @@ func TestWebsocketListen(t *testing.T) {
}
defer c.Close()
buf := make([]byte, 32)
n, err := c.Read(buf)
obr := iotest.OneByteReader(c)
out, err := ioutil.ReadAll(obr)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(buf[:n], msg) {
t.Fatal("got wrong message", buf[:n], msg)
if !bytes.Equal(out, msg) {
t.Fatal("got wrong message", out, msg)
}
}

Loading…
Cancel
Save