Concurrency 戈朗防止渠道堵塞

Concurrency 戈朗防止渠道堵塞,concurrency,go,channel,Concurrency,Go,Channel,我正在构建一个使用WebSocket的服务器。 当前,每个连接的客户端都使用两个goroutine。一个用于阅读,一个用于写作。 编写goroutine基本上会侦听一个通道,寻找它应该发送的消息,然后尝试传递它们 type User struct{ send chan []byte ... } func (u *User) Send(msg []byte){ u.send <- msg } 类型用户结构{ 发送chan[]字节 ... } func(u*用户)发

我正在构建一个使用WebSocket的服务器。
当前,每个连接的客户端都使用两个goroutine。一个用于阅读,一个用于写作。 编写goroutine基本上会侦听一个通道,寻找它应该发送的消息,然后尝试传递它们

type User struct{
    send chan []byte
    ...
}

func (u *User) Send(msg []byte){
    u.send <- msg
}
类型用户结构{
发送chan[]字节
...
}
func(u*用户)发送(消息[]字节){

u、 发送正如ThunderCat在评论中指出的,解决方案是

func (u *User) Send(msg []byte){
    select{
    case u.send <- msg:
    default: //Error handling here
    }
}
func(u*用户)发送(消息[]字节){
挑选{

case u.send使用select和默认子句,如中所示。
func (u *User) Send(msg []byte){
    select{
    case u.send <- msg:
    default: //Error handling here
    }
}