Golang避免通道阻塞

6

我正在构建一个使用Websockets的服务器。
当前每个连接的客户端都使用两个goroutines。一个用于读取,一个用于写入。 写入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
}

基本上,我希望在缓冲区已满的情况下进行错误处理,而不是阻塞。

我该如何最好地实现这一点?


4
请在代码中使用带有默认分支的 select,就像这个 WebSocket 示例中所示。 - Charlie Tumahai
1个回答

6
正如ThunderCat在评论中指出的那样,解决方案是:
func (u *User) Send(msg []byte){
    select{
    case u.send <- msg:
    default: //Error handling here
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接