Started connection handling

This commit is contained in:
Matthias Fulz 2019-11-08 02:14:36 +01:00
parent 2fd55f1183
commit d0a8a238f6
1 changed files with 63 additions and 10 deletions

View File

@ -4,6 +4,8 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"log"
"net"
"olznet.de/ssob" "olznet.de/ssob"
"reflect" "reflect"
"sync" "sync"
@ -44,11 +46,52 @@ type Server struct {
serviceMap sync.Map serviceMap sync.Map
} }
func NewServer() *Server { func (server *Server) ServeConn(conn net.Conn) {
return &Server{} 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) { func (server *Server) RegisterName(name string, rcvr interface{}) (err error) {
if _, ok := server.serviceMap.Load(name); ok { if _, ok := server.serviceMap.Load(name); ok {
@ -116,19 +159,29 @@ func (server *Server) RegisterName(name string, rcvr interface{}) (err error) {
return nil 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 b bytes.Buffer
var fs service
encoder := ssob.NewEncoder(&b) 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 { for _, a := range args {
if err := encoder.Encode(a); err != nil { if err := encoder.Encode(a); err != nil {
fmt.Println(err) return nil, errors.New("srpc: Error: '" + err.Error() + "'")
return nil
} }
} }
inputs := fs.(service).fin(b.Bytes()) inputs := fs.fin(b.Bytes())
outputs := fs.(service).f.Call(inputs) outputs := fs.f.Call(inputs)
return fs.(service).fout(outputs) return fs.fout(outputs), nil
} }
func NewServer() *Server {
return &Server{}
}
var DefaultServer = NewServer()