rename done channel

pass {conn}.Listen() an error channel
This commit is contained in:
onyx-and-iris 2024-11-04 14:42:31 +00:00
parent 2461a0116c
commit f749fbd4b4
2 changed files with 16 additions and 11 deletions

View File

@ -42,15 +42,15 @@ func (c UDPConn) Write(buf []byte) (int, error) {
return n, nil return n, nil
} }
func (c UDPConn) Listen(timeout time.Duration, resp chan<- string) { func (c UDPConn) Listen(timeout time.Duration, resp chan<- string, errChan chan<- error) {
c.conn.SetReadDeadline(time.Now().Add(timeout)) c.conn.SetReadDeadline(time.Now().Add(timeout))
ch := make(chan struct{}) done := make(chan struct{})
var sb strings.Builder var sb strings.Builder
buf := make([]byte, 2048) buf := make([]byte, 2048)
for { for {
select { select {
case <-ch: case <-done:
resp <- sb.String() resp <- sb.String()
return return
default: default:
@ -59,13 +59,14 @@ func (c UDPConn) Listen(timeout time.Duration, resp chan<- string) {
e, ok := err.(net.Error) e, ok := err.(net.Error)
if ok { if ok {
if e.Timeout() { if e.Timeout() {
close(ch) close(done)
} else { } else {
log.Error(e) errChan <- e
return
} }
} }
} }
if rlen == 0 { if rlen < len(c.response.Header()) {
continue continue
} }

View File

@ -7,7 +7,6 @@ import (
"github.com/onyx-and-iris/q3rcon/internal/conn" "github.com/onyx-and-iris/q3rcon/internal/conn"
"github.com/onyx-and-iris/q3rcon/internal/packet" "github.com/onyx-and-iris/q3rcon/internal/packet"
log "github.com/sirupsen/logrus"
) )
// Option is a functional option type that allows us to configure the VbanTxt. // Option is a functional option type that allows us to configure the VbanTxt.
@ -50,7 +49,7 @@ func New(host string, port int, password string, options ...Option) (*Rcon, erro
r := &Rcon{ r := &Rcon{
conn: conn, conn: conn,
request: packet.NewRequest(password), request: packet.NewRequest(password),
resp: make(chan string, 1), resp: make(chan string),
defaultTimeout: 20 * time.Millisecond, defaultTimeout: 20 * time.Millisecond,
timeouts: make(map[string]time.Duration), timeouts: make(map[string]time.Duration),
} }
@ -97,14 +96,19 @@ func (r Rcon) Send(cmd string) (string, error) {
timeout = r.defaultTimeout timeout = r.defaultTimeout
} }
go r.conn.Listen(timeout, r.resp) e := make(chan error)
go r.conn.Listen(timeout, r.resp, e)
_, err := r.conn.Write(r.request.Encode(cmd)) _, err := r.conn.Write(r.request.Encode(cmd))
if err != nil { if err != nil {
return "", err return "", err
} }
log.Tracef("Sending '%s'", cmd)
return strings.TrimPrefix(<-r.resp, string(r.response.Header())), nil select {
case err := <-e:
return "", err
case resp := <-r.resp:
return strings.TrimPrefix(resp, string(r.response.Header())), nil
}
} }
func (r Rcon) Close() { func (r Rcon) Close() {