登录
首页 >  Golang >  Go问答

golang,如何判断一个链接5分钟内无任何消息

来源:SegmentFault

时间:2023-01-26 15:52:31 456浏览 收藏

本篇文章向大家介绍《golang,如何判断一个链接5分钟内无任何消息》,主要包括go,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

请问如何实现一个tcp链接5分钟无消息的话服务器就关闭这个链接呢?希望高手可以帮忙解答一下

正确答案

断开是由server端断开还是client端?client设置超时时间就可以。server端如果用了nginx可以用nginx,
go 的话就用net.Conn的setdeadline
文档代码

// 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
    

意思就是设置读写超时时间,过了时间没有读写就抛出timeout,如果时间内读写成功,则刷新过期时间。这应该就是你想要的。

文中关于golang的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《golang,如何判断一个链接5分钟内无任何消息》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表