3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-13 07:29:30 +01:00
ergo/irc/socket.go
2014-02-23 17:16:35 -08:00

124 lines
2.1 KiB
Go

package irc
import (
"bufio"
"io"
"log"
"net"
"strings"
)
const (
R = '→'
W = '←'
EOF = ""
)
type Socket struct {
closed bool
conn net.Conn
reader *bufio.Reader
client *Client
writer *bufio.Writer
}
func NewSocket(conn net.Conn, client *Client, commands chan<- Command) *Socket {
socket := &Socket{
conn: conn,
reader: bufio.NewReader(conn),
client: client,
writer: bufio.NewWriter(conn),
}
go socket.readLines(commands)
return socket
}
func (socket *Socket) String() string {
return socket.conn.RemoteAddr().String()
}
func (socket *Socket) Close() {
if socket.closed {
return
}
socket.closed = true
socket.conn.Close()
if DEBUG_NET {
log.Printf("%s closed", socket)
}
}
func (socket *Socket) readLines(commands chan<- Command) {
hostnameLookup := &ProxyCommand{
hostname: AddrLookupHostname(socket.conn.RemoteAddr()),
}
hostnameLookup.SetClient(socket.client)
commands <- hostnameLookup
for {
line, err := socket.reader.ReadString('\n')
if socket.isError(err, R) {
socket.closed = true
break
}
line = strings.TrimRight(line, "\r\n")
if len(line) == 0 {
continue
}
if DEBUG_NET {
log.Printf("%s → %s", socket, line)
}
msg, err := ParseCommand(line)
if err != nil {
// TODO error messaging to client
continue
}
msg.SetClient(socket.client)
commands <- msg
}
msg := &QuitCommand{
message: "connection closed",
}
msg.SetClient(socket.client)
commands <- msg
}
func (socket *Socket) Write(line string) (err error) {
if socket.closed {
return io.EOF
}
if _, err = socket.writer.WriteString(line); socket.isError(err, W) {
socket.closed = true
return
}
if _, err = socket.writer.WriteString(CRLF); socket.isError(err, W) {
socket.closed = true
return
}
if err = socket.writer.Flush(); socket.isError(err, W) {
socket.closed = true
return
}
if DEBUG_NET {
log.Printf("%s ← %s", socket, line)
}
return
}
func (socket *Socket) isError(err error, dir rune) bool {
if err != nil {
if DEBUG_NET && (err != io.EOF) {
log.Printf("%s %c error: %s", socket, dir, err)
}
return true
}
return false
}