3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-29 15:40:02 +01:00
ergo/irc/socket.go

105 lines
1.7 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
"log"
"net"
"strings"
)
2014-02-18 08:58:02 +01:00
const (
R = '→'
W = '←'
EOF = ""
2014-02-18 08:58:02 +01:00
)
2014-02-14 04:37:16 +01:00
type Socket struct {
2014-02-20 03:13:35 +01:00
conn net.Conn
reader *bufio.Reader
writer *bufio.Writer
2014-02-14 04:37:16 +01:00
}
2014-02-24 07:21:39 +01:00
func NewSocket(conn net.Conn, commands chan<- editableCommand) *Socket {
2014-02-14 04:37:16 +01:00
socket := &Socket{
2014-02-20 03:13:35 +01:00
conn: conn,
reader: bufio.NewReader(conn),
2014-02-20 03:13:35 +01:00
writer: bufio.NewWriter(conn),
2014-02-14 04:37:16 +01:00
}
go socket.readLines(commands)
2014-02-14 04:37:16 +01:00
return socket
}
func (socket *Socket) String() string {
return socket.conn.RemoteAddr().String()
}
func (socket *Socket) Close() {
2014-02-20 03:13:35 +01:00
socket.conn.Close()
if DEBUG_NET {
log.Printf("%s closed", socket)
2014-02-14 04:37:16 +01:00
}
}
2014-02-24 07:21:39 +01:00
func (socket *Socket) readLines(commands chan<- editableCommand) {
commands <- &ProxyCommand{
hostname: AddrLookupHostname(socket.conn.RemoteAddr()),
}
for {
line, err := socket.reader.ReadString('\n')
2014-02-18 08:58:02 +01:00
if socket.isError(err, R) {
2014-02-14 04:37:16 +01:00
break
}
2014-02-27 01:17:44 +01:00
line = strings.TrimRight(line, CRLF)
2014-02-17 07:24:49 +01:00
if len(line) == 0 {
continue
}
2014-02-14 04:37:16 +01:00
if DEBUG_NET {
log.Printf("%s → %s", socket, line)
}
msg, err := ParseCommand(line)
if err != nil {
// TODO error messaging to client
continue
}
commands <- msg
2014-02-14 04:37:16 +01:00
}
2014-02-24 07:21:39 +01:00
commands <- &QuitCommand{
message: "connection closed",
}
2014-02-14 04:37:16 +01:00
}
func (socket *Socket) Write(line string) (err error) {
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-02-20 03:13:35 +01:00
if err = socket.writer.Flush(); socket.isError(err, W) {
return
}
2014-02-20 20:15:42 +01:00
2014-02-20 03:13:35 +01:00
if DEBUG_NET {
log.Printf("%s ← %s", socket, line)
2014-02-18 08:58:02 +01:00
}
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 {
if DEBUG_NET && (err != io.EOF) {
2014-02-18 08:58:02 +01:00
log.Printf("%s %c error: %s", socket, dir, err)
2014-02-14 04:37:16 +01:00
}
return true
}
return false
}