Skip to content

Close handshake not working correctly #164

@nhooyr

Description

@nhooyr

Was reported to me on reddit by @skwair.

Reproducible example:

package main

import (
	"context"
	"fmt"
	"time"

	"nhooyr.io/websocket"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	c, _, err := websocket.Dial(ctx, "ws://localhost:3333", nil)
	if err != nil {
		// ...
	}
	defer c.Close(websocket.StatusInternalError, "the sky is falling")

	go func() {
		_, _, err := c.Read(context.TODO())
		fmt.Println("failed to read:", err)
	}()

	fmt.Println(c.Close(websocket.StatusNormalClosure, ""))
}
package main

import (
	"context"
	"log"
	"net/http"
	"time"

	"nhooyr.io/websocket"
	"nhooyr.io/websocket/wsjson"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, nil)
		if err != nil {
			// ...
		}
		defer c.Close(websocket.StatusInternalError, "the sky is falling")

		ctx, cancel := context.WithTimeout(r.Context(), time.Second*10)
		defer cancel()

		var v interface{}
		err = wsjson.Read(ctx, c, &v)
		if err != nil {
			log.Println(err)
			return
			// ...
		}

		log.Printf("received: %v", v)

		c.Close(websocket.StatusNormalClosure, "")
	})

	http.ListenAndServe(":3333", nil)
}

Definitely some sort of race condition as it works normally sometimes for me but interestingly enough the client side Read in the other goroutine returns a nil error.

Will fix ASAP.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions