【发布时间】:2015-04-22 11:05:45
【问题描述】:
我正在构建一个使用 websockets 的服务器。
目前,每个连接的客户端都使用两个 goroutine。一个用来读,一个用来写。
写作 goroutine 基本上是在一个通道中监听它应该发送的消息,然后尝试传递它们。
type User struct{
send chan []byte
...
}
func (u *User) Send(msg []byte){
u.send <- msg
}
问题是,从客户端 A 读取可能会导致向客户端 B 写入。 假设与 B 的连接有一些问题(例如非常慢)并且它的发送通道已经满了。当前的行为是,尝试向通道添加消息现在开始阻塞,直到从通道中删除某些内容。 这意味着,现在 A 一直等到 B 的缓冲区不再满。
我想像这样解决它:
func (u *User) Send(msg []byte) err{
u.send, err <- msg
if err != nil{
//The channels buffer is full.
//Writing currently not possible.
//Needs appropriate error handling.
return err
}
return nil
}
基本上,我希望在缓冲区已满时进行错误处理,而不是阻塞。 我怎样才能做到最好?
【问题讨论】:
-
将 select 与 this websocket example 中的默认子句一起使用。
标签: concurrency go channel