3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-14 07:59:31 +01:00
ergo/irc/socket.go

96 lines
1.5 KiB
Go
Raw Normal View History

2014-02-14 04:37:16 +01:00
package irc
import (
"bufio"
"io"
2014-02-14 04:37:16 +01:00
"net"
)
2014-02-18 08:58:02 +01:00
const (
R = '→'
W = '←'
2014-02-18 08:58:02 +01:00
)
2014-02-14 04:37:16 +01:00
type Socket struct {
closed bool
conn net.Conn
scanner *bufio.Scanner
writer *bufio.Writer
2014-02-14 04:37:16 +01:00
}
func NewSocket(conn net.Conn) *Socket {
return &Socket{
conn: conn,
scanner: bufio.NewScanner(conn),
writer: bufio.NewWriter(conn),
2014-02-14 04:37:16 +01:00
}
}
func (socket *Socket) String() string {
return socket.conn.RemoteAddr().String()
}
func (socket *Socket) Close() {
if socket.closed {
return
}
socket.closed = true
2014-02-20 03:13:35 +01:00
socket.conn.Close()
2014-03-09 00:01:15 +01:00
Log.debug.Printf("%s closed", socket)
2014-02-14 04:37:16 +01:00
}
func (socket *Socket) Read() (line string, err error) {
if socket.closed {
err = io.EOF
return
}
for socket.scanner.Scan() {
line = socket.scanner.Text()
2014-02-17 07:24:49 +01:00
if len(line) == 0 {
continue
}
2014-03-09 00:01:15 +01:00
Log.debug.Printf("%s → %s", socket, line)
return
2014-02-14 04:37:16 +01:00
}
err = socket.scanner.Err()
socket.isError(err, R)
if err == nil {
err = io.EOF
}
return
2014-02-14 04:37:16 +01:00
}
func (socket *Socket) Write(line string) (err error) {
if socket.closed {
err = io.EOF
return
}
2014-02-20 03:13:35 +01:00
if _, err = socket.writer.WriteString(line); socket.isError(err, W) {
return
2014-02-18 18:45:10 +01:00
}
2014-02-18 08:58:02 +01:00
2014-02-20 20:15:42 +01:00
if _, err = socket.writer.WriteString(CRLF); socket.isError(err, W) {
return
}
2014-03-29 19:56:23 +01:00
if err = socket.writer.Flush(); socket.isError(err, W) {
return
}
2014-02-20 20:15:42 +01:00
2014-03-09 00:01:15 +01:00
Log.debug.Printf("%s ← %s", socket, line)
2014-02-20 03:13:35 +01:00
return
2014-02-14 04:37:16 +01:00
}
2014-02-18 08:58:02 +01:00
func (socket *Socket) isError(err error, dir rune) bool {
2014-02-14 04:37:16 +01:00
if err != nil {
2014-03-09 00:01:15 +01:00
if err != io.EOF {
Log.debug.Printf("%s %c error: %s", socket, dir, err)
2014-02-14 04:37:16 +01:00
}
return true
}
return false
}