Golang Websocket客户端关闭了连接

I have a golang connection. If the client opened the connection the database change the online column to 1. Here is my code but I didnt implement the last thing. My question, how can I change the database column to 0 if the client closed the connection. How can I track the client, and catch the connection close?

package main

import (
    "golang.org/x/net/websocket"
    "fmt"
    "log"
    "net/http"

    "strconv"
)

type Clients struct {
    webs *websocket.Conn
    clientAddr string
    id int
}

var (
    ActiveClients = make(map[Clients]int)
)

func Echo(ws *websocket.Conn){
    var err error

    client := ws.Request().RemoteAddr
    sockCli := Clients{webs: ws, clientAddr: client, id: 0}
    ActiveClients[sockCli] = 1


    for{
        var reply string

        if err = websocket.Message.Receive(ws, &reply); err != nil{
            fmt.Println("Cant receive", err)
            break
        }else{
            if sockCli.id == 0{
                sockCli.id, err = strconv.Atoi(reply)

            }
        }


        if err = websocket.Message.Send(ws, "id:"+strconv.Itoa(sockCli.id)); err != nil{
            fmt.Println("Cant send")
        }



        for cs, _ := range ActiveClients {
            if cs.id == 1{
                if err = websocket.Message.Send(cs.webs, "asd"); err != nil {
                    // we could not send the message to a peer
                    log.Println("Could not send message to ", cs.clientAddr, err.Error())
                }
            }else {
                fmt.Println("No")
            }



        }


    }

}

func main(){
    http.Handle("/", websocket.Handler(Echo))

    if err := http.ListenAndServe(":1234", nil); err != nil{
        log.Fatal("ListenAndServe: ", err)
    }
}
dsdv76767671
dsdv76767671 请使用种族探测器运行您的代码。如果您在此处构建示例,则在并发负载下它将崩溃。
接近 5 年之前 回复
drflkphi675447
drflkphi675447 在线列从1到0。但是,我通过并发检查客户端映射的功能解决了该问题。
接近 5 年之前 回复
dongyi0210
dongyi0210 从多个goroutine访问ActiveClients是一场数据竞赛-您至少需要使用互斥锁对其进行保护。当您遇到读取或写入错误时,您会知道何时关闭连接。您要更改哪个“数据库”列?
接近 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐