Repository navigation
Closed
Description
It's very possible I'm using this wrong, but pulling from your echo example, and your tests, a simple ping test with the following fails:
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"time"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
)
func main() {
l, err := net.Listen("tcp", "localhost:0")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
defer l.Close()
s := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := pingServer(w, r)
if err != nil {
log.Printf("echo server: %v", err)
}
}),
ReadTimeout: time.Second * 15,
WriteTimeout: time.Second * 15,
}
defer s.Close()
go func() {
err := s.Serve(l)
if err != http.ErrServerClosed {
log.Fatalf("failed to listen and serve: %v", err)
}
}()
err = client("ws://" + l.Addr().String())
if err != nil {
log.Fatalf("client failed: %v", err)
}
}
func pingServer(w http.ResponseWriter, r *http.Request) error {
c, err := websocket.Accept(w, r, nil)
if err != nil {
return err
}
defer c.Close(websocket.StatusInternalError, "the sky is falling")
log.Println("Pinging client")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
err = c.Ping(ctx)
if err != nil {
return err
}
return nil
}
func client(url string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
c, _, err := websocket.Dial(ctx, url, nil)
if err != nil {
return err
}
defer c.Close(websocket.StatusInternalError, "the sky is falling")
for {
v := map[string]int{}
err = wsjson.Read(ctx, c, &v)
if err != nil {
return err
}
fmt.Printf("received: %v\n", v)
}
c.Close(websocket.StatusNormalClosure, "")
return nil
}Output:
2020/02/10 22:09:42 Pinging client
2020/02/10 22:09:47 echo server: failed to ping: failed to wait for pong: context deadline exceeded
2020/02/10 22:09:47 client failed: failed to read json: failed to get reader: failed to read frame header: read tcp 127.0.0.1:51279->127.0.0.1:51278: read: connection reset by peer
exit status 1
Is there a different way this is supposed to be used? Thanks for any insight!
Metadata
Metadata
Assignees
Labels
No labels
Activity
nhooyr commentedon Feb 11, 2020
So you send a ping but because you are never reading in the server goroutine, the pong is never read.
See the docs on the Ping method.
nhooyr commentedon Feb 11, 2020
https://godoc.org/nhooyr.io/websocket#Conn.Ping
nhooyr commentedon Feb 11, 2020
If you explicitly want to ignore messages, use
c.CloseReadand then your example will work.nhooyr commentedon Feb 11, 2020
This succeeds with:
Now only the client fails.
pmwebster commentedon Feb 11, 2020
Thanks for clarifying that! The docs make perfect sense now. Cheers!
csrar commentedon Dec 11, 2020
I'm not sure if did it wright but because I have spend a day trying to make work the ping functionality I'm leaving an example how I'm using it