Created
June 9, 2013 02:14
-
-
Save DexterHaslem/5737348 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"errors" | |
"fmt" | |
"net" | |
) | |
const QUEUE_SIZE = 512 | |
type ConnectionEvent func(err error) | |
type IRCConnection struct { | |
socket *net.TCPConn | |
read_queue, write_queue chan string | |
Writer chan<- string | |
OnDisconnected ConnectionEvent | |
OnConnected ConnectionEvent | |
// | |
Connected bool | |
} | |
func CreateIRCConnection() *IRCConnection { | |
read_queue := make(chan string, QUEUE_SIZE) | |
write_queue := make(chan string, QUEUE_SIZE) | |
return &IRCConnection{nil, read_queue, write_queue, write_queue, nil, nil, false} | |
} | |
func (connection *IRCConnection) Connect(server string) error { | |
if connection.socket != nil { | |
return errors.New("Already connected") | |
} | |
address, error := net.ResolveTCPAddr("tcp", server) | |
if error != nil { | |
return error | |
} | |
socket, error := net.DialTCP("tcp", nil, address) | |
if error != nil { | |
return error | |
} | |
connection.Connected = true | |
connection.OnConnected(nil) | |
buffered_reader := bufio.NewReader(socket) | |
buffered_writer := bufio.NewWriter(socket) | |
writer := make(chan string, QUEUE_SIZE) | |
go func() { | |
for { | |
// forever read loop | |
in_str, err := buffered_reader.ReadString(byte('\n')) | |
if err != nil { | |
fmt.Printf("reader: %s\n", err) | |
connection.OnDisconnected(err) | |
break | |
} | |
connection.read_queue <- in_str[0 : len(in_str)-2] // len -2 chops \r\n right off | |
} | |
}() | |
go func() { | |
for { | |
// forever write loop | |
out_str := <-writer | |
//if closed(writer) { break; } | |
_, err := buffered_writer.WriteString(out_str + "\r\n") | |
if err != nil { | |
fmt.Printf("writer: %s\n", err) | |
connection.OnDisconnected(err) | |
break | |
} | |
buffered_writer.Flush() | |
} | |
}() | |
connection.write_queue = writer | |
connection.Writer = writer | |
connection.socket = socket | |
//return errors.New("Not implemented") | |
return nil | |
} | |
func (connection *IRCConnection) SendRaw(msg string) { | |
connection.write_queue <- msg | |
} | |
func (connection *IRCConnection) ReadRaw() string { | |
return <-connection.read_queue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment