feat: client.Run 支持传入 block 参数指定客户端以阻塞的模式运行

This commit is contained in:
kercylan98 2023-09-21 15:46:20 +08:00
parent 13c5483617
commit 534a7e962a
1 changed files with 13 additions and 3 deletions

View File

@ -32,17 +32,21 @@ type Client struct {
closed bool // 是否已关闭
pool *concurrent.Pool[*Packet] // 数据包缓冲池
loop *writeloop.WriteLoop[*Packet] // 写入循环
block chan struct{} // 以阻塞方式运行
}
// Run 运行客户端
// - 当客户端已运行时,会先关闭客户端再重新运行
func (slf *Client) Run() error {
// Run 运行客户端,当客户端已运行时,会先关闭客户端再重新运行
// - block 以阻塞方式运行
func (slf *Client) Run(block ...bool) error {
slf.mutex.Lock()
if !slf.closed {
slf.mutex.Unlock()
slf.Close()
slf.mutex.Lock()
}
if len(block) > 0 && block[0] {
slf.block = make(chan struct{})
}
var runState = make(chan error)
go func(runState chan<- error) {
defer func() {
@ -77,6 +81,9 @@ func (slf *Client) Run() error {
slf.mutex.Unlock()
slf.OnConnectionOpenedEvent(slf)
if slf.block != nil {
<-slf.block
}
return nil
}
@ -100,6 +107,9 @@ func (slf *Client) Close(err ...error) {
} else {
slf.OnConnectionClosedEvent(slf, nil)
}
if slf.block != nil {
slf.block <- struct{}{}
}
}
// WriteWS 向连接中写入指定 websocket 数据类型