Websocket to TCP bridge

477 views
Skip to first unread message

Joseph Naegele

unread,
Jan 20, 2017, 2:29:56 PM1/20/17
to Gorilla web toolkit
Hi folks, I'm trying to implement a basic version of websockify using Gorilla websocket, however calling conn.NextReader() the first time appears to block forever.

My current attempt looks like this (with error handling removed):

upgrader := websocket.Upgrader{
   
ReadBufferSize:  4096,
   
WriteBufferSize: 4096,
   
Subprotocols:    []string{"binary"},
   
CheckOrigin: func(r *http.Request) bool { return true },
}

handler
:= func(w http.ResponseWriter, r *http.Request) {
    wsconn
, err := upgrader.Upgrade(w, r, nil)
    defer wsconn
.Close()

    conn
, err := net.Dial("tcp", ":5900")
    defer conn
.Close()

    writer
, err := wsconn.NextWriter(websocket.BinaryMessage)
    defer writer
.Close()

    _
, reader, err := wsconn.NextReader()

    go io
.Copy(conn, reader)
    io
.Copy(writer, conn)
}

mux
:= http.NewServeMux()
mux
.HandleFunc("/websockify", handler)

Note that I *am* checking all errors in my code (there aren't any). I've also tried changing the order of calling NextReader/NextWriter and dialing my remote TCP connection, as well as calling NextReader in an entirely different goroutine.

The following works when using golang.org/x/net/websocket:

handleWss := func(wsconn *websocket.Conn) {
    conn
, err := net.Dial("tcp", ":8080")
   
if err != nil {
        wsconn
.Close()
   
} else {
        wsconn
.PayloadType = websocket.BinaryFrame

        go io
.Copy(conn, wsconn)
        io
.Copy(wsconn, conn)
   
}
}

bootHandshake
:= func(config *websocket.Config, r *http.Request) error {
    config
.Protocol = []string{"binary"}
    r
.Header.Set("Access-Control-Allow-Origin", "*")
    r
.Header.Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
   
return nil
}

handler
:= websocket.Server{Handshake: bootHandshake, Handler: handleWss}
mux
:= http.NewServeMux()
mux
.Handle("/websockify", handler)

Is my problem obvious? Any clues?

Thanks,
Joe


Reply all
Reply to author
Forward
Message has been deleted
0 new messages