golang中怎么处理socket长连接
答案:1 悬赏:0 手机版
解决时间 2021-03-24 08:11
- 提问者网友:原来太熟悉了会陌生
- 2021-03-23 07:59
golang中怎么处理socket长连接
最佳答案
- 五星知识达人网友:掌灯师
- 2021-03-23 09:28
实际上需要 3 个 goroutine,一个 read,一个 send,还有一个 handle。
read goroutine 读,然后写入 recevice chan。
write goroutine 把 send chan 的东西写。
handle goroutine 是 conn 的主要处理逻辑,负责把 recevice chan 的东西读出来 call 业务逻辑。
业务逻辑中要写数据就直接写入 send chan。
这样就可以保证,业务逻辑的读写都是在 handle goroutine 上处理,而避免 race 产生。
如果需要定时任务(比如心跳),就在 handle goroutine 上加上一个 timer.C;
read goroutine 读,然后写入 recevice chan。
write goroutine 把 send chan 的东西写。
handle goroutine 是 conn 的主要处理逻辑,负责把 recevice chan 的东西读出来 call 业务逻辑。
业务逻辑中要写数据就直接写入 send chan。
这样就可以保证,业务逻辑的读写都是在 handle goroutine 上处理,而避免 race 产生。
如果需要定时任务(比如心跳),就在 handle goroutine 上加上一个 timer.C;
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯