diff --git a/conn.go b/conn.go index 49ee73c..34b1d1d 100644 --- a/conn.go +++ b/conn.go @@ -13,6 +13,7 @@ import ( "time" "github.com/gopherjs/gopherjs/js" + "honnef.co/go/js/console" "honnef.co/go/js/dom" ) @@ -23,19 +24,53 @@ func beginHandlerOpen(ch chan error, removeHandlers func()) func(ev *js.Object) } } +// closeErrorMap maps Close frame status codes to their string explanation +// See http://tools.ietf.org/html/rfc6455#section-7.4.1 +var closeErrorMap = map[int]string{ + 1000: "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.", + 1001: "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.", + 1002: "An endpoint is terminating the connection due to a protocol error", + 1003: "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).", + 1004: "Reserved. The specific meaning might be defined in the future.", + 1005: "No status code was actually present.", + 1006: "The connection was closed abnormally, e.g., without sending or receiving a Close control frame", + 1007: "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).", + 1008: "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.", + 1009: "An endpoint is terminating the connection because it has received a message that is too big for it to process.", + // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead + 1010: "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake.", + 1011: "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.", + 1015: "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).", +} + // closeError allows a CloseEvent to be used as an error. type closeError struct { *dom.CloseEvent } func (e *closeError) Error() string { - var cleanStmt string + var ( + cleanStmt string + reason string // cant override the event's reason + ok bool + ) if e.WasClean { cleanStmt = "clean" } else { cleanStmt = "unclean" + + if e.Reason != "" { + reason = e.Reason + } else { + reason, ok = closeErrorMap[e.Code] + if !ok { + reason = "Unknown reason" + } + } + } - return fmt.Sprintf("CloseEvent: (%s) (%d) %s", cleanStmt, e.Code, e.Reason) + + return fmt.Sprintf("CloseEvent: (%s) (%d) %s", cleanStmt, e.Code, reason) } func beginHandlerClose(ch chan error, removeHandlers func()) func(ev *js.Object) { @@ -72,6 +107,7 @@ func Dial(url string) (*Conn, error) { ch: make(chan *dom.MessageEvent, 1), } conn.initialize() + conn.Reader, conn.pw = io.Pipe() openCh := make(chan error, 1) @@ -101,6 +137,8 @@ func Dial(url string) (*Conn, error) { return nil, err } + go conn.receiveLoop() + return conn, nil } @@ -115,6 +153,10 @@ type Conn struct { readBuf *bytes.Reader readDeadline time.Time + + io.Reader + pw *io.PipeWriter + closeErr *closeError } func (c *Conn) onMessage(event *js.Object) { @@ -125,6 +167,11 @@ func (c *Conn) onMessage(event *js.Object) { func (c *Conn) onClose(event *js.Object) { go func() { + if ce, ok := dom.WrapEvent(event).(*dom.CloseEvent); ok { + c.closeErr = &closeError{CloseEvent: ce} + console.Error(c.closeErr.Error()) + } + // We queue nil to the end so that any messages received prior to // closing get handled first. c.ch <- nil @@ -147,7 +194,11 @@ func (c *Conn) initialize() { // convenience funciton to dedupe code for the multiple deadline cases. func (c *Conn) handleFrame(item *dom.MessageEvent, ok bool) (*dom.MessageEvent, error) { if !ok { // The channel has been closed - return nil, io.EOF + if c.closeErr == nil { + return nil, io.EOF + + } + return nil, c.closeErr } else if item == nil { // See onClose for the explanation about sending a nil item. close(c.ch) @@ -157,6 +208,31 @@ func (c *Conn) handleFrame(item *dom.MessageEvent, ok bool) (*dom.MessageEvent, return item, nil } +// receiveLoop fill's the writer end of the Conn's io.Pipe with data frames +// runs in its own goroutine +func (c *Conn) receiveLoop() { + + for { + frame, err := c.receiveFrame(true) + if err != nil { + if err2 := c.pw.CloseWithError(err); err2 != nil { + console.Error("CloseWithError failed", err2) + } + return + } + + receivedBytes := getFrameData(frame.Data) + + _, err = io.Copy(c.pw, bytes.NewReader(receivedBytes)) + if err != nil { + if err2 := c.pw.CloseWithError(err); err2 != nil { + console.Error("CloseWithError failed", err2) + } + return + } + } +} + // receiveFrame receives one full frame from the WebSocket. It blocks until the // frame is received. func (c *Conn) receiveFrame(observeDeadline bool) (*dom.MessageEvent, error) { @@ -197,41 +273,11 @@ func getFrameData(obj *js.Object) []byte { return []byte(obj.String()) } -func (c *Conn) Read(b []byte) (n int, err error) { - if c.readBuf != nil { - n, err = c.readBuf.Read(b) - if err == io.EOF { - c.readBuf = nil - err = nil - } - // If we read nothing from the buffer, continue to trying to receive. - // This saves us when the last Read call emptied the buffer and this - // call triggers the EOF. There's probably a better way of doing this, - // but I'm really tired. - if n > 0 { - return - } - } - - frame, err := c.receiveFrame(true) - if err != nil { - return 0, err - } - - receivedBytes := getFrameData(frame.Data) - - n = copy(b, receivedBytes) - // Fast path: The entire frame's contents have been copied into b. - if n >= len(receivedBytes) { - return - } - - c.readBuf = bytes.NewReader(receivedBytes[n:]) - return -} - // Write writes the contents of b to the WebSocket using a binary opcode. func (c *Conn) Write(b []byte) (n int, err error) { + if c.closeErr != nil { + return 0, c.closeErr + } // []byte is converted to an (U)Int8Array by GopherJS, which fullfils the // ArrayBufferView definition. err = c.Send(b)