Golang websocket 空指针内存错误

huangapple go评论162阅读模式
英文:

Golang websocket nil memory error

问题

以下是我的websocket服务器的代码。

http.Handle("/gatewayconnector", websocket.Handler(socketHandler))

func socketHandler(ws *websocket.Conn) {
    LoadClient(ws)
    var msg []byte
    for {
        if err := websocket.Message.Receive(ws, &msg); err != nil {
            log.Error("Error in socketHandler: ", err)
            break
        }
        validateMessage(msg)
    }
}

当客户端发起握手并初始化websocket对象时,socketHandler回调方法会被调用。因此,在这个方法的第一步中,我将websocket对象存储在一个数组中,以便在发送方法调用时(用于向客户端发送消息)可以检索到它。

问题是,有时候当我尝试向客户端发送消息时,ws即websocket会出现空指针引用的情况。

以下是发送方法的代码:

func Send(msg interface{}) error {
    ws := webSocketClients[0]
    if ws == nil {
        log.Error("Websocket connection is nil, gateway should initiate the connection.")
    }
    return websocket.JSON.Send(ws, msg)
}

当websocket连接空闲一段时间并且我直接调用发送方法时,就会出现这个问题。

目前,我已经采取了一个解决方法,即客户端会定期向我的websocket服务器发送ping请求,以避免这个问题。

如何避免这种问题?

英文:

Below is the code of my websocket server.

http.Handle("/gatewayconnector", websocket.Handler(socketHandler))

Method socketHandler has the code below:

func socketHandler(ws *websocket.Conn) {
    LoadClient(ws)
    var msg []byte
    for {
        if err := websocket.Message.Receive(ws, &msg); err != nil {
	        log.Error("Error in socketHandler: ", err)
            break
        }
	    validateMessage(msg)
    }
}

The socket handler call back method get called when handshake happened from client and it also initiate the websocket object. So at very first step of this method i stored this websocket object into an array, so that i can retrieve it at the send method call (used to send message to client).

The issue is sometimes I'm getting nil memory reference in ws i.e. the websocket while trying to send some message to client.

Below is the send method code:

func Send(msg interface{}) error {
    ws := webSocketClients[0]
    if (ws == nil) {
        log.Error("Websocket connection is nil, gateway should initiate the connection.")
    }
    return websocket.JSON.Send(ws, msg)
}

This issue arises when websocket connection remanis idle for a longer persiod of time and I call directly the send method.

Right now i have put one hack that client will ping my websocket server at regular interval to avoid this.

How to avoid this kind of problem?

答案1

得分: 1

在间隔期内对WebSocket连接进行ping操作是一种正常的做法,请查看Gorilla Websocket Chat Example中的实现方式。我知道你正在使用net/websocket,但是思路应该是相似的。问题在于,你不能指望长时间的TCP连接会一直保持活动状态,特别是在公共网络中。一些防火墙会在一段时间后静默地重置没有流量的连接。

英文:

Pinging websocket connection on interval is normal thing to do, please check how it's done in Gorilla Websocket Chat Example. I know you're using net/websocket, but the idea should be similar. The problem is that you can't rely that your long-time TCP connection will remain active, especially in public networks. Some firewalls silently RST connections without traffic flow after some period of time.

huangapple
  • 本文由 发表于 2016年2月2日 14:37:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/35146671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定