2012-04-07 20:44:59 +02:00
|
|
|
package irc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net"
|
2012-04-18 07:21:41 +02:00
|
|
|
"time"
|
2012-04-07 20:44:59 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
2012-04-18 07:21:41 +02:00
|
|
|
ctime time.Time
|
2012-04-18 07:11:35 +02:00
|
|
|
name string
|
2012-04-18 03:16:57 +02:00
|
|
|
ch chan *ClientMessage
|
2012-04-08 08:32:08 +02:00
|
|
|
nicks map[string]*Client
|
2012-04-07 20:44:59 +02:00
|
|
|
}
|
|
|
|
|
2012-04-18 03:16:57 +02:00
|
|
|
type ClientMessage struct {
|
|
|
|
client *Client
|
|
|
|
message Message
|
|
|
|
}
|
|
|
|
|
2012-04-18 07:11:35 +02:00
|
|
|
func NewServer(name string) *Server {
|
2012-04-18 03:16:57 +02:00
|
|
|
server := new(Server)
|
2012-04-18 07:21:41 +02:00
|
|
|
server.ctime = time.Now()
|
2012-04-18 07:11:35 +02:00
|
|
|
server.name = name
|
2012-04-18 03:16:57 +02:00
|
|
|
server.ch = make(chan *ClientMessage)
|
|
|
|
server.nicks = make(map[string]*Client)
|
2012-04-07 20:44:59 +02:00
|
|
|
go server.Receive()
|
2012-04-18 03:16:57 +02:00
|
|
|
return server
|
2012-04-07 20:44:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) Listen(addr string) {
|
|
|
|
listener, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
2012-04-08 08:32:08 +02:00
|
|
|
log.Fatal("Server.Listen: ", err)
|
2012-04-07 20:44:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
for {
|
|
|
|
conn, err := listener.Accept()
|
|
|
|
if err != nil {
|
2012-04-08 08:32:08 +02:00
|
|
|
log.Print("Server.Listen: ", err)
|
2012-04-07 20:44:59 +02:00
|
|
|
continue
|
|
|
|
}
|
2012-04-18 03:16:57 +02:00
|
|
|
go NewClient(conn).Communicate(s.ch)
|
2012-04-07 20:44:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) Receive() {
|
2012-04-18 03:16:57 +02:00
|
|
|
for m := range s.ch {
|
|
|
|
m.message.Handle(s, m.client)
|
2012-04-09 16:57:55 +02:00
|
|
|
}
|
2012-04-07 20:44:59 +02:00
|
|
|
}
|