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