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

133 lines
2.1 KiB
Go
Raw Normal View History

2014-02-14 04:37:16 +01:00
package irc
import (
"bufio"
"log"
"net"
"strings"
)
2014-02-18 08:58:02 +01:00
const (
R = '→'
W = '←'
)
2014-02-14 04:37:16 +01:00
type Socket struct {
2014-02-18 08:58:02 +01:00
closed bool
2014-02-14 04:37:16 +01:00
conn net.Conn
2014-02-18 08:58:02 +01:00
done chan bool
2014-02-14 04:37:16 +01:00
reader *bufio.Reader
receive chan string
2014-02-14 08:16:07 +01:00
send chan string
writer *bufio.Writer
2014-02-14 04:37:16 +01:00
}
func NewSocket(conn net.Conn) *Socket {
socket := &Socket{
conn: conn,
2014-02-18 08:58:02 +01:00
done: make(chan bool),
2014-02-14 04:37:16 +01:00
reader: bufio.NewReader(conn),
receive: make(chan string),
send: make(chan string),
writer: bufio.NewWriter(conn),
}
go socket.readLines()
go socket.writeLines()
return socket
}
func (socket *Socket) String() string {
return socket.conn.RemoteAddr().String()
}
func (socket *Socket) Close() {
2014-02-18 08:58:02 +01:00
if socket.closed {
return
}
socket.closed = true
socket.done <- true
close(socket.done)
2014-02-14 04:37:16 +01:00
}
func (socket *Socket) Read() <-chan string {
return socket.receive
}
2014-02-18 08:58:02 +01:00
func (socket *Socket) Write(lines ...string) {
2014-02-14 04:37:16 +01:00
for _, line := range lines {
socket.send <- line
}
return
2014-02-14 04:37:16 +01:00
}
func (socket *Socket) readLines() {
2014-02-14 05:38:22 +01:00
for {
2014-02-14 04:37:16 +01:00
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
}
line = strings.TrimRight(line, "\r\n")
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)
}
socket.receive <- line
}
2014-02-18 08:58:02 +01:00
close(socket.receive)
2014-02-18 08:58:02 +01:00
if DEBUG_NET {
log.Printf("%s closed", socket)
}
2014-02-14 04:37:16 +01:00
}
func (socket *Socket) writeLines() {
2014-02-18 08:58:02 +01:00
done := false
for !done {
select {
case line := <-socket.send:
if _, err := socket.writer.WriteString(line); socket.isError(err, W) {
break
}
if _, err := socket.writer.WriteString(CRLF); socket.isError(err, W) {
break
}
2014-02-18 08:58:02 +01:00
if err := socket.writer.Flush(); socket.isError(err, W) {
break
}
if DEBUG_NET {
log.Printf("%s ← %s", socket, line)
}
case done = <-socket.done:
continue
2014-02-14 04:37:16 +01:00
}
}
2014-02-18 08:58:02 +01:00
if DEBUG_NET {
log.Printf("%s closing", socket)
}
socket.conn.Close()
for _ = range socket.send {
// discard lines
}
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 {
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
}