简体   繁体   English

Golang阻止通道阻塞

[英]Golang prevent channel from blocking

I am building a server that uses websockets. 我正在构建一个使用websockets的服务器。
Currently every connected client uses two goroutines. 目前,每个连接的客户端都使用两个goroutine。 One for reading and one for writing. 一个用于阅读,一个用于写作。 The writing goroutine basically listens to a channel for messages it should send and then tries to deliver them. 写作goroutine基本上会收听它应该发送的消息的频道,然后尝试传递它们。

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

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

Problem is, that a read from client A may cause a write to client B. Suppose the connection to B has some problems however (eg very slow) and it's send channel is already full. 问题是,从客户端A读取可能会导致写入客户端B.假设与B的连接有一些问题(例如非常慢)并且它的发送通道已经满了。 Current behaviour is, that trying to add a message to the channel now starts blocking, until something is removed from the channel. 目前的行为是,尝试向频道添加消息现在开始阻止,直到从频道中删除某些内容。 This means, that now A waits until B's buffer is no longer full. 这意味着,现在A等待B的缓冲区不再满。

I want to solve it somewhat like this: 我想解决它有点像这样:

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
}

Basically instead of blocking I want error handling in case the buffer is full. 基本上不是阻塞我想要缓冲区已满的错误处理。 How do I achieve that best? 我如何做到最好?

As ThunderCat pointed out in his comment the solution is 正如ThunderCat在他的评论中指出的那样,解决方案是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM