dtuct88226 2018-12-21 07:18
浏览 344

GoLang TCP连接-远程网络已关闭检查

I am creating a GoLang application and clients are android phones. I am able to handle connections. If user closes the android application connection is dropped with EOF

My problem is, if client just turn off wifi network connection is still alive.

Here is my code

func main() {
    fmt.Println("Starting server...")
    connection, err := net.Listen("tcp", ":4406")

    if err != nil {
        fmt.Println(err)
    }
    defer connection.Close()
    manager := ClientManager{
        clients:    make(map[*Client]bool),
        broadcast:  make(chan []byte),
        register:   make(chan *Client),
    }

    go manager.start()
    for {
        connection, _ := connection.Accept()
        if err != nil {
            fmt.Println(err)
        }
        client := &Client{socket: connection, data: make(chan []byte), uuid: connection.RemoteAddr().String()}

        manager.register <- client
        go manager.receive(client)
        go handleConnection(client)
    }

}

Handeling connections

func handleConnection(client *Client) {

    conn := client.socket
    defer conn.Close()
    notify := make(chan error)
    go func() {
        buf := make([]byte, 1024)
        for {
            n, err := conn.Read(buf)
            if err != nil {
                notify <- err
                return
            }
            if n > 0 {
                fmt.Println("unexpected data: %s", buf[:n])
            }
        }
    }()

    for {
        select {
        case err := <-notify:
            if err != nil {
                fmt.Println("connection dropped message", err)
                return
            }
        case <-time.After(time.Second * 1):
            fmt.Println("timeout 1, still alive")
        }
    }
}

When remote wifi is off (cable removed) I want to disconnect the user. I tried to read a byte and every second and it is reading it. I sent a byte and it is sent as well.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

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