modularize

This commit is contained in:
Jeffrey Paul 2019-08-19 18:56:27 -05:00
parent c72ee3e495
commit 3fcdd86089
3 changed files with 49 additions and 25 deletions

View File

@ -1,12 +1,18 @@
package main
import "log"
import "os"
import "sircd"
import "sync"
import "time"
func main() {
l := log.New(os.Stdout, "", log.Ldate | log.Lmicroseconds | log.Lshortfile)
l.Println("sircd starting up")
s := sircd.NewSircd()
s.Start()
s.SetLogger(l)
go s.Start()
for s.Running {
time.Sleep(100 * time.Millisecond)
time.Sleep(1 * time.Second)
}
}

22
src/sircd/client.go Normal file
View File

@ -0,0 +1,22 @@
package sircd
import (
"net"
"os"
"log"
)
type clientIRCConnection struct {
conn net.Conn
log *log.Logger
}
func (c *clientIRCConnection) Read() *[]byte {
buf := make([]byte, 1024*1024)
// Read the incoming connection into the buffer.
_, err := c.conn.Read(buf)
if err != nil {
s.log.Println("Error reading:", err.Error())
}
return &buf
}

View File

@ -1,13 +1,14 @@
package sircd
import (
"fmt"
"net"
"os"
"log"
)
type sircd struct {
Running bool
log *log.Logger
netName string
ircPort uint16
httpPort uint16
@ -15,10 +16,6 @@ type sircd struct {
ircClients []*clientIRCConnection
}
type clientIRCConnection struct {
conn net.Conn
}
const (
CONN_HOST = "localhost"
CONN_PORT = "6667"
@ -31,49 +28,48 @@ func NewSircd() *sircd {
return s
}
func (s *sircd) startServer() {
func (s *sircd) SetLogger(l *log.Logger) {
s.log = l
}
func (s *sircd) startIRCServer() {
var err error
s.ircListener, err = net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
if err != nil {
fmt.Println("Error listening:", err.Error())
log.Println("Error listening:", err.Error())
os.Exit(1)
}
defer s.ircListener.Close()
fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
fmt.Printf("%T\n",s.ircListener)
s.log.Println("Listening for irc on " + CONN_HOST + ":" + CONN_PORT)
for {
// Listen for an incoming connection.
conn, err := s.ircListener.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
os.Exit(1)
s.log.Fatalf("Error accepting: ", err.Error())
}
// Handle connections in a new goroutine.
go handleRequest(conn)
go s.handleIRCConnection(conn)
}
}
func (s *sircd) Start() {
go func() {
s.startServer()
}()
go s.startIRCServer()
}
// Handles incoming requests.
func handleRequest(conn net.Conn) {
// Make a buffer to hold incoming data.
buf := make([]byte, 1024)
// Read the incoming connection into the buffer.
byteLen, err := conn.Read(buf)
func (s *sircd) handleIRCConnection(conn net.Conn) {
c := new(clientIRCConnection)
c.conn = conn
c.log = s.log
if err != nil {
fmt.Println("Error reading:", err.Error())
c.log.Println("Error reading:", err.Error())
}
// Send a response back to person contacting us.
conn.Write([]byte("Message received."))
fmt.Println("Received message (%i bytes): %s", byteLen, buf)
s.log.Println("Received message (%i bytes): %s", byteLen, buf)
// Close the connection when you're done with it.
conn.Close()
}