dongzhan7909 2016-12-28 05:49
浏览 179
已采纳

在Golang中设置连接生命的时间

I am a novice in golang and I am writing a client-server application through the TCP protocol. I need to make a temporary connection, which will close after a couple of seconds. I don't understand how to do that.
I have a such function, which creates a connection and waits for gob data:

    func net_AcceptAppsList(timesleep time.Duration) {
        ln, err := net.Listen("tcp", ":"+conf.PORT)
        CheckError(err)
        conn, err := ln.Accept()
        CheckError(err)
        dec := gob.NewDecoder(conn)
        pack := map[string]string{}
        err = dec.Decode(&pack)
        fmt.Println("Message:", pack)
        conn.Close()
}

I need to make this function to wait for data for only some seconds - not forever.

  • 写回答

2条回答 默认 最新

  • dongpi2503 2016-12-28 13:52
    关注

    Use SetDeadline or SetReadDeadline

    From the net.Conn docs

        // SetDeadline sets the read and write deadlines associated
        // with the connection. It is equivalent to calling both
        // SetReadDeadline and SetWriteDeadline.
        //
        // A deadline is an absolute time after which I/O operations
        // fail with a timeout (see type Error) instead of
        // blocking. The deadline applies to all future I/O, not just
        // the immediately following call to Read or Write.
        //
        // An idle timeout can be implemented by repeatedly extending
        // the deadline after successful Read or Write calls.
        //
        // A zero value for t means I/O operations will not time out.
        SetDeadline(t time.Time) error
    
        // SetReadDeadline sets the deadline for future Read calls.
        // A zero value for t means Read will not time out.
        SetReadDeadline(t time.Time) error
    
        // SetWriteDeadline sets the deadline for future Write calls.
        // Even if write times out, it may return n > 0, indicating that
        // some of the data was successfully written.
        // A zero value for t means Write will not time out.
        SetWriteDeadline(t time.Time) error
    

    If you want the Accept call to timeout, you can use the TCPListener.SetDeadline method.

    ln.(*net.TCPListener).SetDeadline(time.Now().Add(time.Second))
    

    Optionally, you could have a timer call Close() or CloseRead() on the connection, or Close() on the net.Listener, but that won't leave you with the cleaner timeout error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探