douzhang5984 2015-12-20 21:26
浏览 454

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)
    }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 保护模式-系统加载-段寄存器