我想在浏览器中使用WebSocket JSON-RPC服务器示例。当您访问URL“http:localhost:8080”时,浏览器会正确打开WebSocket连接。但是当浏览器发送WebSocket请求时,服务器会关闭WebSocket连接。我甚至看不到在服务器上调用RPC方法的痕迹。
但是,从Go客户端调用服务器可以很好地工作。
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)
}
网络/ 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)
}
你知道问题是什么吗?
非常感谢。
干杯