dnssecsocket/example-channel-goroutine/server.go

66 lines
1.3 KiB
Go

package main
import "fmt"
import "log"
import "net"
import "os"
import "io"
import "bytes"
import "github.com/golang/protobuf/proto"
import pb "git.wit.com/jcarr/witProtobuf"
func processEvents(mychannel chan *pb.Event) {
for {
message := <-mychannel
log.Println("processEvents() on channel recieved a message")
ReadReceivedData(message)
}
}
func ReadReceivedData(data *pb.Event) {
msgItems := data.GetResults()
fmt.Println("Receiving data...")
for _, item := range msgItems {
fmt.Println(item)
}
}
func main() {
fmt.Println("Staring Server..")
c := make(chan *pb.Event)
go processEvents(c)
listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
for {
if conn, err := listener.Accept(); err == nil {
go handleProtoClient(conn, c)
} else {
continue
}
}
}
func handleProtoClient(conn net.Conn, c chan *pb.Event) {
fmt.Println("Connected!")
defer conn.Close()
var buf bytes.Buffer
_, err := io.Copy(&buf, conn)
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
return
}
pdata := new(pb.Event)
err = proto.Unmarshal(buf.Bytes(), pdata)
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
return
}
c <- pdata
}