go routine - 为什么websocket将连接报告为关闭?

时间:2015-08-07 06:03:25

标签: go websocket

我正在尝试使用Go创建客户端和服务器但由于某种原因服务器将连接报告为“已关闭”。由于代码很简单,我无法想到我的代码有什么问题。任何帮助表示赞赏。

package main

import (
    log "github.com/golang/glog"
    "net/http"
    "golang.org/x/net/websocket"
    "time"
    "flag"
)

type server struct {
    payload chan string
}

// srv pushes the messages received via ws into srv.payload
func (srv *server) serve(ws *websocket.Conn) {
    go func() {
        var msg string
        if err := websocket.Message.Receive(ws, &msg); err != nil {
            log.Exit(err)
        }
        srv.payload <- msg
    }()
    return
}

// This example demonstrates a trivial client/ server.
func main() {
    flag.Parse()
    srv := server{payload: make(chan string, 10)}
    http.Handle("/echo", websocket.Handler(srv.serve))
    go func() {
        err := http.ListenAndServe(":12345", nil)
        if err != nil {
            log.Errorf("ListenAndServe: " + err.Error())
        }
    }()
    // give the server some time to start listening
    time.Sleep(3 *time.Second)
    //dial and test the response.
    ws, err := websocket.Dial("ws://localhost:12345/echo", "", "http://localhost/?x=45")
    if err != nil {
        log.Exit(err)
    }
    ms := "test"
    if err := websocket.Message.Send(ws, ms); err != nil {
        log.Exit(err)
    }
    msg := <-srv.payload
    if msg != ms{
        log.Errorf("msg %v is not %v", ms)
    }

}

错误

 t.go:21] read tcp 127.0.0.1:12345->127.0.0.1:43135: 

修改 经过一些尝试和错误后,我发现如果我从服务方法中删除了go例程它可以工作,但对我来说没有意义。想知道为什么当websocket.Message.Receive处于一个单独的go例程时它为什么不起作用?

package main

import (
    log "github.com/golang/glog"
    "net/http"
    "golang.org/x/net/websocket"
    "time"
    "flag"
)

type server struct {
    payload chan string
}

// srv pushes the messages received via ws into srv.payload
func (srv *server) serve(ws *websocket.Conn) {
        var msg string
        if err := websocket.Message.Receive(ws, &msg); err != nil {
            log.Exit(err)
        }
        srv.payload <- msg 
    return
}

// This example demonstrates a trivial client/ server.
func main() {
    flag.Parse()
    srv := server{payload: make(chan string, 10)}

    go func() {
        http.Handle("/echo", websocket.Handler(srv.serve))
        err := http.ListenAndServe(":12345", nil)
        if err != nil {
            log.Errorf("ListenAndServe: " + err.Error())
        }
    }()
    // give the server some time to start listening
    time.Sleep(3 *time.Second)
    //dial and test the response.
    ws, err := websocket.Dial("ws://localhost:12345/echo", "", "http://localhost/?x=45")
    if err != nil {
        log.Exit(err)
    }
    ms := "test"
    if err := websocket.Message.Send(ws, ms); err != nil {
        log.Exit(err)
    }
    msg := <-srv.payload
    if msg != ms{
        log.Errorf("msg %v is not %v", ms)
    }

}

1 个答案:

答案 0 :(得分:1)

处理程序返回时的websocket服务器closes the connection

删除Go例程是正确的解决方法。