douran9707 2014-05-07 13:46
浏览 426

Golang Server关闭客户端的连接:websocket

i have a problem with my golang server in which i'm using websockets. The server opens the connection and the client could connect to it, but the problem is that when the server starts sending the data to the client, the client connection is closed after a small period of time. i suggest that the problem is with the server and not with the client because i tried to connect to the server with another web client, and it's the same issue. I didn't understand the cause ! Can someone help me?

server.go:

    func Echo(ws *websocket.Conn) {
    fmt.Println("Echoing")

         for {
        msg := MessageReceived{Name: "OrderCommand", Nbmsg: 3}

        if err := websocket.JSON.Send(ws, msg); err != nil {
            fmt.Println("Can't send")
            break
        }

    //os.Exit(0)
         }
}

func checkError(err error) {
    if err != nil {
        Log("Fatal error ", err.Error())
        os.Exit(1)
    }
}


func main() {

    http.HandleFunc("/save", saveHandler)
    http.Handle("/", websocket.Handler(Echo))
    err:= http.ListenAndServe(":8081", nil)
    checkError(err)

}

and client.go:

 import (
    "code.google.com/p/go.net/websocket"
    "fmt"
    "log"
)

func main() {
    origin := "http://localhost/"
    url := "ws://localhost:8081/echo"
    ws, err := websocket.Dial(url, "", origin)
    if err != nil {
        log.Fatal(err)
    }

    var msg = make([]byte, 512)
    var n int
    if n, err = ws.Read(msg); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Received: %s.
", msg[:n])
}
  • 写回答

2条回答 默认 最新

  • doukong9316 2014-05-07 15:04
    关注

    Why using ws.Read when you can use websocket.JSON.Receive to deserialize the message?

    Here are the server: http://play.golang.org/p/NZ6VJ4daGm and the client: http://play.golang.org/p/rkJVKGhrGk (that I have changed to receive 10 messages before exiting).

    The string "Can't send" will be printed by the server once the client closes the websocket connection.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度