From d0a8a238f638099621c2ad1b9c2c328a51442894 Mon Sep 17 00:00:00 2001 From: Matthias Fulz Date: Fri, 8 Nov 2019 02:14:36 +0100 Subject: [PATCH] Started connection handling --- server.go | 73 +++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 63 insertions(+), 10 deletions(-) diff --git a/server.go b/server.go index dc99fa5..1939e7d 100644 --- a/server.go +++ b/server.go @@ -4,6 +4,8 @@ import ( "bytes" "errors" "fmt" + "log" + "net" "olznet.de/ssob" "reflect" "sync" @@ -44,11 +46,52 @@ type Server struct { serviceMap sync.Map } -func NewServer() *Server { - return &Server{} +func (server *Server) ServeConn(conn net.Conn) { + var b bytes.Buffer + var fs service + size := int64(0) + name := string("") + + dec := ssob.NewDecoder(&b) + + sizeb := make([]byte, 12) + conn.Read(sizeb) + + b.Write(sizeb) + dec.Decode(&size) + log.Println(size) + + payload := make([]byte, size) + conn.Read(payload) + b.Reset() + b.Write(payload) + log.Println(b.Bytes()) + + dec.Decode(&name) + log.Println(name) + + if fsRaw, ok := server.serviceMap.Load(name); !ok { + log.Printf("srpc: Call to unknown method: '%s'", name) + return + } else { + fs = fsRaw.(service) + } + + inputs := fs.fin(b.Bytes()) + outputs := fs.f.Call(inputs) + log.Println(outputs) } -var DefaultServer = NewServer() +func (server *Server) Accept(ln net.Listener) { + for { + conn, err := ln.Accept() + if err != nil { + log.Printf("srpc: accept: %s", err.Error()) + return + } + go server.ServeConn(conn) + } +} func (server *Server) RegisterName(name string, rcvr interface{}) (err error) { if _, ok := server.serviceMap.Load(name); ok { @@ -116,19 +159,29 @@ func (server *Server) RegisterName(name string, rcvr interface{}) (err error) { return nil } -func (server *Server) CallName(name string, args ...interface{}) (ret []byte) { +func (server *Server) CallName(name string, args ...interface{}) (ret []byte, err error) { var b bytes.Buffer + var fs service encoder := ssob.NewEncoder(&b) - fs, _ := server.serviceMap.Load(name) + if fsRaw, ok := server.serviceMap.Load(name); !ok { + return nil, errors.New("srpc: Call to unknown method: '" + name + "'") + } else { + fs = fsRaw.(service) + } for _, a := range args { if err := encoder.Encode(a); err != nil { - fmt.Println(err) - return nil + return nil, errors.New("srpc: Error: '" + err.Error() + "'") } } - inputs := fs.(service).fin(b.Bytes()) - outputs := fs.(service).f.Call(inputs) - return fs.(service).fout(outputs) + inputs := fs.fin(b.Bytes()) + outputs := fs.f.Call(inputs) + return fs.fout(outputs), nil } + +func NewServer() *Server { + return &Server{} +} + +var DefaultServer = NewServer()