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

1
2
3
4
5
6
7
8
type User struct{
    send chan []byte
    ...
}

func (u *User) Send(msg []byte){
    u.send <- msg
}

问题是,从客户端A读取可能导致对客户端B的写入。
但是,假设与B的连接存在一些问题(例如,速度很慢),并且其发送通道已满。 当前的行为是,尝试将消息添加到通道现在开始阻塞,直到从通道中删除了某些内容为止。
这意味着,现在A等待直到B的缓冲区不再满。

我想这样解决它:

1
2
3
4
5
6
7
8
9
10
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
}

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

  • 在此websocket示例中,使用select with default子句。

正如ThunderCat在其评论中指出的,解决方案是

1
2
3
4
5
6
func (u *User) Send(msg []byte){
    select{
    case u.send <- msg:
    default: //Error handling here
    }
}