driver is functional
This commit is contained in:
parent
df036ec680
commit
7dd0faf24b
3 changed files with 90 additions and 5 deletions
|
|
@ -5,10 +5,13 @@ import (
|
|||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ClosedError = errors.New("sonic connection is closed")
|
||||
|
||||
type Connection struct {
|
||||
Host string
|
||||
Port int
|
||||
|
|
@ -17,6 +20,7 @@ type Connection struct {
|
|||
|
||||
reader *bufio.Reader
|
||||
conn net.Conn
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (c *Connection) Connect() error {
|
||||
|
|
@ -45,12 +49,21 @@ func (c *Connection) Connect() error {
|
|||
}
|
||||
}
|
||||
|
||||
func (c Connection) read() (string, error) {
|
||||
func (c *Connection) read() (string, error) {
|
||||
if c.closed {
|
||||
return "", ClosedError
|
||||
}
|
||||
buffer := bytes.Buffer{}
|
||||
for {
|
||||
line, isPrefix, err := c.reader.ReadLine()
|
||||
buffer.Write(line)
|
||||
if err != nil || !isPrefix {
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
c.clean()
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
if !isPrefix {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
|
@ -63,6 +76,43 @@ func (c Connection) read() (string, error) {
|
|||
}
|
||||
|
||||
func (c Connection) write(str string) error {
|
||||
if c.closed {
|
||||
return ClosedError
|
||||
}
|
||||
_, err := c.conn.Write([]byte(str + "\r\n"))
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Connection) Quit() error {
|
||||
err := c.write("QUIT")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// should get ENDED
|
||||
_, err = c.read()
|
||||
c.clean()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Connection) Ping() error {
|
||||
err := c.write("PING")
|
||||
if err != nil {
|
||||
fmt.Println("err write")
|
||||
return err
|
||||
}
|
||||
|
||||
// should get PONG
|
||||
_, err = c.read()
|
||||
if err != nil {
|
||||
fmt.Println("err read")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Connection) clean() {
|
||||
c.closed = true
|
||||
_ = c.conn.Close()
|
||||
c.conn = nil
|
||||
c.reader = nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue