dnssecsocket/emaild/server.go

119 lines
2.4 KiB
Go

// inspired from:
// https://github.com/mactsouk/opensource.com.git
// and
// https://coderwall.com/p/wohavg/creating-a-simple-tcp-server-in-go
package main
// import "fmt"
// import "os"
import "math/rand"
import "net"
import "time"
import "log"
import "bufio"
import "strings"
import "strconv"
import "github.com/davecgh/go-spew/spew"
const (
CONN_HOST = "localhost"
CONN_PORT = "9000"
CONN_TYPE = "tcp"
)
/*
// the simplest handler of them all
// just write everything from the socket to stdout
go func(c net.Conn) {
defer c.Close()
io.Copy(os.Stdout, c)
}(conn)
*/
func random() int {
return rand.Intn(50) + 4
}
func main() {
listenstr := "[" + "localhost" + "]:" + CONN_PORT
log.Println("listenstr", listenstr)
myTCPAddr, err := net.ResolveTCPAddr("tcp", listenstr)
// // Listen for incoming connections on the IPv6 address only
l, err := net.ListenTCP("tcp", myTCPAddr)
if err != nil {
log.Println("Error listening:", err.Error())
return
}
// Close the listener when the application closes.
defer l.Close()
log.Println("Listening on " + listenstr)
rand.Seed(time.Now().Unix())
for {
// Listen for an incoming connection.
conn, err := l.AcceptTCP()
if err != nil {
log.Println("Error accepting: ", err.Error())
return
}
log.Println("Accepted new connection from: " + conn.RemoteAddr().String())
// Handle connections in a new goroutine.
go HandleConnection(conn)
}
}
//
// Handle each connection
// Each client must send it's hostname as the first line
// Then each hostname is verified with DNSSEC
//
func HandleConnection(conn *net.TCPConn) {
ipv6client := conn.RemoteAddr()
log.Println("Serving to %s as the IPv6 client", ipv6client)
// setup this TCP socket as the "standard input"
// newStdin, _ := bufio.NewReader(conn.File())
newStdin, _ := conn.File()
newreader := bufio.NewReader(newStdin)
log.Println("Waiting for the client to tell me its name")
netData, err := newreader.ReadString('\n')
spew.Dump(netData)
log.Println("netData =", string(netData))
if err != nil {
log.Println(err)
return
}
// f, _ := conn.File()
for {
defer conn.Close()
netData, err := newreader.ReadString('\n')
if err != nil {
log.Println(err)
return
}
temp := strings.TrimSpace(string(netData))
if temp == "STOP" {
break
}
log.Println("Recieved: ", temp)
result := strconv.Itoa(random()) + "\n"
conn.Write([]byte(string(result)))
return
}
}