FAQ
Hi everyone,

I have a WebSocket JSON-RPC server example that I want to use from a
browser. When you access the URL "http:localhost:8080", the browser opens
the WebSocket connection properly. But when the browser sends the WebSocket
request, the server closes the WebSocket connection. I can't even see a
trace of the RPC method being called on the server.

However, calling the server from a Go client works perfectly.

It seems that the problem is how jsonrpc handles the incoming message. But
I don't know what is going wrong.

*server.go*
package main


import (
         "log"
         "net/http"
         "net/rpc"
         "net/rpc/jsonrpc"
         "github.com/gorilla/websocket"
)


type Service struct{}


func (t *Service) Echo(req *string, res *string) error {
         log.Printf("Service.Echo")
         *res = *req
         log.Printf("Service.Echo req:%s res:%s", *req, *res)
         return nil
}


var upgrader = websocket.Upgrader{
         ReadBufferSize: 1024,
         WriteBufferSize: 1024,
}


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


         if err != nil {
                 log.Println(err)
                 return
         }
         jsonrpc.ServeConn(ws.UnderlyingConn())
}


func main() {
         rpc.Register(new(Service))
         http.Handle("/", http.FileServer(http.Dir("web")))
         http.HandleFunc("/ws", serveWS)
         http.ListenAndServe(":8080", nil)
}

*web/index.html*
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
     var ws = new WebSocket("ws://localhost:8080/ws");
     ws.onopen = function(ev){
         alert("open");
     }
     ws.onmessage = function(ev){
         alert("message");
     }
     ws.onclose = function(ev){
         alert("close");
     }

     function send() {
         msg = {
                 method: "Service.Echo",
                 params: "hello",
                 id: 0
         };
         var s = JSON.stringify(msg);
         alert(s);
         ws.send(s);
     }
</script>
</head>
<body>
<button onclick='send()'>Send</button>
</body>
</html>

*client.go*
package main


import (
         "log"
         "net/rpc/jsonrpc"
         "github.com/gorilla/websocket"
)


func main() {
         ws, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080/ws",
  nil)
         if err != nil {
                 log.Fatal("dial:", err)
         }
         defer ws.Close()

         client := jsonrpc.NewClient(ws.UnderlyingConn())


         req := "hello"
         var res string
         err = client.Call("Service.Echo", &req, &res)
         if err != nil {
                 log.Fatal("Service.Echo error:", err)
         }
         log.Printf("Service.Echo: req:%s res:%s", req, res)
}

Do you know what the problem could be?

Thank you very much.

Cheers,
Alvaro

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

  • C Banning at Apr 2, 2016 at 2:44 pm
    need to put the jsonrpc.ServeConn() in a for {...} loop or your handler
    will close and ws.Close() will execute.
    On Saturday, April 2, 2016 at 6:21:58 AM UTC-5, Alvaro wrote:

    Hi everyone,

    I have a WebSocket JSON-RPC server example that I want to use from a
    browser. When you access the URL "http:localhost:8080", the browser opens
    the WebSocket connection properly. But when the browser sends the WebSocket
    request, the server closes the WebSocket connection. I can't even see a
    trace of the RPC method being called on the server.

    However, calling the server from a Go client works perfectly.

    It seems that the problem is how jsonrpc handles the incoming message. But
    I don't know what is going wrong.

    *server.go*
    package main


    import (
    "log"
    "net/http"
    "net/rpc"
    "net/rpc/jsonrpc"
    "github.com/gorilla/websocket"
    )


    type Service struct{}


    func (t *Service) Echo(req *string, res *string) error {
    log.Printf("Service.Echo")
    *res = *req
    log.Printf("Service.Echo req:%s res:%s", *req, *res)
    return nil
    }


    var upgrader = websocket.Upgrader{
    ReadBufferSize: 1024,
    WriteBufferSize: 1024,
    }


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


    if err != nil {
    log.Println(err)
    return
    }
    jsonrpc.ServeConn(ws.UnderlyingConn())
    }


    func main() {
    rpc.Register(new(Service))
    http.Handle("/", http.FileServer(http.Dir("web")))
    http.HandleFunc("/ws", serveWS)
    http.ListenAndServe(":8080", nil)
    }

    *web/index.html*
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <script type="text/javascript">
    var ws = new WebSocket("ws://localhost:8080/ws");
    ws.onopen = function(ev){
    alert("open");
    }
    ws.onmessage = function(ev){
    alert("message");
    }
    ws.onclose = function(ev){
    alert("close");
    }

    function send() {
    msg = {
    method: "Service.Echo",
    params: "hello",
    id: 0
    };
    var s = JSON.stringify(msg);
    alert(s);
    ws.send(s);
    }
    </script>
    </head>
    <body>
    <button onclick='send()'>Send</button>
    </body>
    </html>

    *client.go*
    package main


    import (
    "log"
    "net/rpc/jsonrpc"
    "github.com/gorilla/websocket"
    )


    func main() {
    ws, _, err := websocket.DefaultDialer.Dial(
    "ws://localhost:8080/ws", nil)
    if err != nil {
    log.Fatal("dial:", err)
    }
    defer ws.Close()

    client := jsonrpc.NewClient(ws.UnderlyingConn())


    req := "hello"
    var res string
    err = client.Call("Service.Echo", &req, &res)
    if err != nil {
    log.Fatal("Service.Echo error:", err)
    }
    log.Printf("Service.Echo: req:%s res:%s", req, res)
    }

    Do you know what the problem could be?

    Thank you very much.

    Cheers,
    Alvaro
    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.
  • Alvaro at Apr 2, 2016 at 3:12 pm
    Ok, thank you very much. But why is it only happening when it is called from a browser?

    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.
  • Alvaro at Apr 2, 2016 at 3:48 pm
    Following it on
    http://stackoverflow.com/questions/36372650/go-websocket-jsonrpc-browser-connection-close

    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.
  • Horst Noreick at Apr 3, 2016 at 2:28 am
    May be it is a testing failure. If you listen on Port 8080, you have to
    load the site in your browser with localhost:8080. The site is not
    delivered by the server, so probably it will be delivered by another http
    server. In this case the browser sends an *Origin: localhost* without the
    portnr but the websocket checks for *Origin:* *localhost:8080*. That means
    the same origin policy is not fullfilled and the request is rejected. You
    can either call localhost in browser with the right portnr or swich off the
    origincheck

    var upgrader = websocket.Upgrader{
         ReadBufferSize: 1024,
         WriteBufferSize: 1024,
           CheckOrigin: func(r *http.Request) bool { return true },
    }

    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedApr 2, '16 at 11:21a
activeApr 3, '16 at 2:28a
posts5
users3
websitegolang.org

People

Translate

site design / logo © 2021 Grokbase