func NewPublisher(ctx context.Context, url string) (*Publisher, error) { var sock mangos.Socket var err error sock, err = pub.NewSocket() if err != nil { return nil, err } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) err = sock.Listen(url) if err != nil { return nil, err } publiser := &Publisher{ ctx: ctx, url: url, sock: sock, publishCh: make(chan []string), } go publiser.run() return publiser, nil }
func (t *inprocTran) NewListener(addr string, sock mangos.Socket) (mangos.PipeListener, error) { if _, err := mangos.StripScheme(t, addr); err != nil { return nil, err } l := &listener{addr: addr, proto: sock.GetProtocol()} return l, nil }
func send(s mangos.Socket, obj interface{}) error { data, err := json.Marshal(obj) if err != nil { return stackerr.Wrap(err) } return stackerr.Wrap(s.Send(data)) }
func replyLoop(sock mangos.Socket, done chan struct{}) { defer close(done) if sendData == nil { fatalf("No data to send!") } for { msg, err := sock.RecvMsg() switch err { case mangos.ErrRecvTimeout: return case nil: default: fatalf("RecvMsg failed: %v", err) } printMsg(msg) msg.Free() msg = mangos.NewMessage(len(sendData)) msg.Body = append(msg.Body, sendData...) err = sock.SendMsg(msg) if err != nil { fatalf("SendMsg failed: %v", err) } } }
func recv(s mangos.Socket, obj interface{}) error { data, err := s.Recv() if err != nil { return stackerr.Wrap(err) } return stackerr.Wrap(json.Unmarshal(data, obj)) }
func recv_name(sock mangos.Socket, name string) { var msg []byte var err error if msg, err = sock.Recv(); err == nil { fmt.Printf("%s: RECEIVED: \"%s\"\n", name, string(msg)) } }
func sendRequest(s mangos.Socket, request request) (*response, error) { fmt.Println("Sending a request") requestJSON, err := json.Marshal(request) if err != nil { // This is not recoverable. panic(err) } fmt.Printf("sendRequest: %s\n", requestJSON) if err := s.Send(requestJSON); err != nil { return nil, err } rep, err := s.Recv() if err != nil { return nil, err } var resp response if err := json.Unmarshal(rep, &resp); err != nil { return nil, err } return &resp, nil }
func send_recv(sock mangos.Socket, name string) { for { sock.SetOption(mangos.OptionRecvDeadline, 100*time.Millisecond) recv_name(sock, name) time.Sleep(time.Second) send_name(sock, name) } }
func publishEvt(channel mangos.Socket, evt string) error { if err := channel.Send([]byte(evt)); err != nil { log.Printf("fail to publish '%v' event:%v\n", evt, err) return err } return nil }
func output(in chan string, out mangos.Socket) { if out == nil { panic("Invalid socket") } for item := range in { out.Send([]byte(item)) } }
func getEvt(channel mangos.Socket) (string, error) { log.Println("getEvt()") evt, err := channel.Recv() if err != nil { return "", err } return string(evt), nil }
func StartNanomsgProtoServer(port string) { var server mangos.Socket var err error if server, err = rep.NewSocket(); err != nil { log.Fatal(err) } server.AddTransport(tcp.NewTransport()) server.Listen("tcp://0.0.0.0:" + port) for { msg, _ := server.Recv() var body pb.Request proto.Unmarshal(msg, &body) data, _ := proto.Marshal(&pb.Response{ Method: body.Method, PayloadLength: int64(len(body.Payload)), }) server.Send(data) } }
func client(url string, name string) { var sock mangos.Socket var err error var msg []byte if sock, err = sub.NewSocket(); err != nil { die("can't get new sub socket: %s", err.Error()) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Dial(url); err != nil { die("can't dial on sub socket: %s", err.Error()) } // Empty byte array effectively subscribes to everything err = sock.SetOption(mangos.OptionSubscribe, []byte("")) if err != nil { die("cannot subscribe: %s", err.Error()) } for { if msg, err = sock.Recv(); err != nil { die("Cannot recv: %s", err.Error()) } fmt.Printf("CLIENT(%s): RECEIVED %s\n", name, string(msg)) } }
func StartNanomsgJsonServer(port string) { var server mangos.Socket var err error if server, err = rep.NewSocket(); err != nil { log.Fatal(err) } server.AddTransport(tcp.NewTransport()) server.Listen("tcp://0.0.0.0:" + port) for { msg, _ := server.Recv() var body Request var response []byte json.Unmarshal(msg, &body) if response, err = json.Marshal(Response{Method: body.Method, PayloadLength: len(body.Payload)}); err != nil { log.Fatal(err) } server.Send(response) } }
func client(url string, name string) { var sock mangos.Socket var err error var msg []byte if sock, err = respondent.NewSocket(); err != nil { die("can't get new respondent socket: %s", err.Error()) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Dial(url); err != nil { die("can't dial on respondent socket: %s", err.Error()) } for { if msg, err = sock.Recv(); err != nil { die("Cannot recv: %s", err.Error()) } fmt.Printf("CLIENT(%s): RECEIVED \"%s\" SURVEY REQUEST\n", name, string(msg)) d := date() fmt.Printf("CLIENT(%s): SENDING DATE SURVEY RESPONSE\n", name) if err = sock.Send([]byte(d)); err != nil { die("Cannot send: %s", err.Error()) } } }
func node0(url string) { var sock mangos.Socket var err error var msg []byte if sock, err = rep.NewSocket(); err != nil { die("can't get new rep socket: %s", err) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Listen(url); err != nil { die("can't listen on rep socket: %s", err.Error()) } for { // Could also use sock.RecvMsg to get header msg, err = sock.Recv() if string(msg) == "DATE" { // no need to terminate fmt.Println("NODE0: RECEIVED DATE REQUEST") d := date() fmt.Printf("NODE0: SENDING DATE %s\n", d) err = sock.Send([]byte(d)) if err != nil { die("can't send reply: %s", err.Error()) } } } }
func (t wsTran) NewListener(addr string, sock mangos.Socket) (mangos.PipeListener, error) { proto := sock.GetProtocol() l, e := t.listener(addr, proto) if e == nil { if v, e := sock.GetOption(mangos.OptionMaxRecvSize); e == nil { l.maxrx = v.(int) } l.mux.Handle(l.url.Path, l) } return l, e }
func node0(url string) { var sock mangos.Socket var err error if sock, err = pair.NewSocket(); err != nil { die("can't get new pair socket: %s", err) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Listen(url); err != nil { die("can't listen on pair socket: %s", err.Error()) } send_recv(sock, "node0") }
func node1(url string) { var sock mangos.Socket var err error if sock, err = pair.NewSocket(); err != nil { die("can't get new pair socket: %s", err.Error()) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Dial(url); err != nil { die("can't dial on pair socket: %s", err.Error()) } sendRecv(sock, "node1") }
func (wsTran) NewDialer(addr string, sock mangos.Socket) (mangos.PipeDialer, error) { iswss := strings.HasPrefix(addr, "wss://") opts := make(map[string]interface{}) opts[mangos.OptionNoDelay] = true opts[mangos.OptionKeepAlive] = true proto := sock.GetProtocol() maxrx := 0 if v, e := sock.GetOption(mangos.OptionMaxRecvSize); e == nil { maxrx = v.(int) } return &dialer{addr: addr, proto: proto, iswss: iswss, opts: opts, maxrx: maxrx}, nil }
func recvLoop(sock mangos.Socket) { for { msg, err := sock.RecvMsg() switch err { case mangos.ErrProtoState: return case mangos.ErrRecvTimeout: return case nil: default: fatalf("RecvMsg failed: %v", err) } printMsg(msg) msg.Free() } }
func simpleSend(t *testing.T, tx mangos.Socket, wg *sync.WaitGroup) { var buf [256]byte i := 0 for i = 0; i < 10000; i++ { l := rand.Intn(255) + 1 buf[0] = uint8(l) if e := tx.Send(buf[:l]); e != nil { t.Fatalf("Send: %v", e) break } } t.Logf("Sent %d Msgs", i) if e := tx.Close(); e != nil { t.Fatalf("Tx Close: %v", e) } wg.Done() }
func Server(urlServer string, urlPubSub string, opt Options) (*DiscoveryServer, error) { var sock mangos.Socket var err error var publisher *Publisher ctx, cancel := context.WithCancel(context.Background()) sock, err = surveyor.NewSocket() if err != nil { return nil, err } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) err = sock.Listen(urlServer) if err != nil { return nil, err } err = sock.SetOption(mangos.OptionSurveyTime, opt.SurveyTime) if err != nil { return nil, err } err = sock.SetOption(mangos.OptionRecvDeadline, opt.RecvDeadline) if err != nil { return nil, err } pubCtx, pubCancel := context.WithCancel(ctx) publisher, err = NewPublisher(pubCtx, urlPubSub) if err != nil { pubCancel() return nil, err } services := NewServices(publisher) server := &DiscoveryServer{ services: services, urlServer: urlServer, urlPubSub: urlPubSub, opt: opt, ctx: ctx, cancel: cancel, sock: sock, } go server.run() return server, nil }
func server(url string, nworkers int) { var sock mangos.Socket var err error var wg sync.WaitGroup rand.Seed(time.Now().UnixNano()) if sock, err = rep.NewSocket(); err != nil { die("can't get new rep socket: %s", err) } if err = sock.SetOption(mangos.OptionRaw, true); err != nil { die("can't set raw mode: %s", err) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Listen(url); err != nil { die("can't listen on rep socket: %s", err.Error()) } wg.Add(nworkers) fmt.Printf("Starting %d workers\n", nworkers) for id := 0; id < nworkers; id++ { go func(id int) { defer wg.Done() serverWorker(sock, id) }(id) } wg.Wait() }
func NewSubscriber(ctx context.Context, url string) (*Subscriber, error) { var sock mangos.Socket var err error sock, err = sub.NewSocket() if err != nil { return nil, err } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) err = sock.Dial(url) if err != nil { return nil, err } // subscribes to everything err = sock.SetOption(mangos.OptionSubscribe, []byte("")) if err != nil { return nil, err } subscriber := &Subscriber{ url: url, ctx: ctx, sock: sock, changes: make(chan []string, 8), } go subscriber.run() return subscriber, nil }
func recvLoop(sock mangos.Socket, done chan struct{}) { defer close(done) for { msg, err := sock.RecvMsg() switch err { case mangos.ErrRecvTimeout: return case nil: default: fatalf("RecvMsg failed: %v", err) } printMsg(msg) msg.Free() if sendInterval == 0 { return } } }
func sendLoop(sock mangos.Socket) { if sendData == nil { fatalf("No data to send!") } for { msg := mangos.NewMessage(len(sendData)) msg.Body = append(msg.Body, sendData...) err := sock.SendMsg(msg) if err != nil { fatalf("SendMsg failed: %v", err) } if sendInterval >= 0 { time.Sleep(time.Duration(sendInterval) * time.Second) } else { break } } }
func ClientWithSub(urlServer string, urlPubSub string, service string) (*DiscoveryClient, error) { var sock mangos.Socket var err error var subscriber *Subscriber ctx, cancel := context.WithCancel(context.Background()) if urlPubSub != "" { subCtx, _ := context.WithCancel(ctx) subscriber, err = NewSubscriber(subCtx, urlPubSub) if err != nil { return nil, err } } sock, err = respondent.NewSocket() if err != nil { return nil, err } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) err = sock.Dial(urlServer) if err != nil { return nil, err } client := &DiscoveryClient{ urlServer: urlServer, urlPubSub: urlPubSub, service: service, ctx: ctx, cancel: cancel, sock: sock, subscriber: subscriber, } go client.run() return client, nil }
func node1(url string, msg string) { var sock mangos.Socket var err error if sock, err = push.NewSocket(); err != nil { die("can't get new push socket: %s", err.Error()) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Dial(url); err != nil { die("can't dial on push socket: %s", err.Error()) } fmt.Printf("NODE1: SENDING \"%s\"\n", msg) if err = sock.Send([]byte(msg)); err != nil { die("can't send message on push socket: %s", err.Error()) } sock.Close() }
func runCmdServer(channel mangos.Socket, done <-chan struct{}) (<-chan string, error) { cmdChan := make(chan string) go func() { for { // Could also use sock.RecvMsg to get header log.Println("alauncher: cmd server - waiting for a command...") select { case <-done: log.Println("alauncher: cmd server - done...") return default: if rawCmd, err := channel.Recv(); err != nil { switch err { case mangos.ErrRecvTimeout: log.Println("alauncher: cmd server - timeout... ok") default: log.Println("alauncher: cmd server - error =>", err) } } else { cmd := string(rawCmd) log.Println("alauncher: cmd server - got a command =>", cmd) cmdChan <- cmd //for now just ack the command and process the command asynchronously //NOTE: //must reply before receiving the next message //otherwise nanomsg/mangos will be confused :-) monitorFinishReply := "ok" err = channel.Send([]byte(monitorFinishReply)) if err != nil { log.Println("alauncher: cmd server - fail to send monitor.finish reply =>", err) } } } } }() return cmdChan, nil }