func TestSimpleCorrect(t *testing.T) { tx, e := pair.NewSocket() if e != nil { t.Fatalf("NewSocket: %v", e) return } rx, e := pair.NewSocket() if e != nil { t.Fatalf("NewSocket: %v", e) return } tx.AddTransport(tcp.NewTransport()) rx.AddTransport(tcp.NewTransport()) if e = rx.Listen(AddrTestTCP); e != nil { t.Fatalf("Listen: %v", e) return } if e = tx.Dial(AddrTestTCP); e != nil { t.Fatalf("Dial: %v", e) return } wg := &sync.WaitGroup{} wg.Add(2) go simpleSend(t, tx, wg) go simpleRecv(t, rx, wg) wg.Wait() }
func main() { flag.Parse() var sock mangos.Socket var err error if sock, err = pub.NewSocket(); err != nil { die("can't get new pub socket: %s", err) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Listen("tcp://127.0.0.1:55555"); err != nil { die("can't listen on pub socket: %s", err.Error()) } //sub var subscriber mangos.Socket if subscriber, err = sub.NewSocket(); err != nil { die("can't get new sub socket: %s", err.Error()) } subscriber.AddTransport(ipc.NewTransport()) subscriber.AddTransport(tcp.NewTransport()) if err = subscriber.Dial("tcp://127.0.0.1:55555"); err != nil { die("can't dial on sub socket: %s", err.Error()) } // Empty byte array effectively subscribes to everything err = subscriber.SetOption(mangos.OptionSubscribe, []byte("")) start := time.Now() //var msg []byte for i := 1; i <= *numbPtr; i++ { //conn.Publish("test", []byte(randSeq(320))) sock.Send([]byte(randSeq(320))) if _, err = subscriber.Recv(); err != nil { die("Cannot recv: %s", err.Error()) } //log.Println(string(msg)) /* runtime.Gosched() atomic.AddUint64(&ops, 1) if ops == uint64(*numbPtr) { elapsed := time.Since(start) log.Printf("Time took %s", elapsed) } */ } elapsed := time.Since(start) log.Printf("Time took %s", elapsed) defer sock.Close() fmt.Scanln() }
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 (publ *Publisher) run() { sock, err := pub.NewSocket() if err != nil { log.Fatalln("pub.NewSocket error:", err) } sock.AddTransport(inproc.NewTransport()) sock.AddTransport(tcp.NewTransport()) defer sock.Close() if publ.Connect { err = sock.Dial(publ.Endpoint) } else { err = sock.Listen(publ.Endpoint) } if err != nil { log.Fatalln("sock connect failed:", err) } // sending on a socket straight away silently fails, so wait 20ms. ugh. time.Sleep(time.Millisecond * 20) for ev := range publ.Channel { // format: topic\0data data := fmt.Sprintf("%s\000%s", ev.Topic, ev.String()) err := sock.Send([]byte(data)) if err != nil { log.Fatalln("Failed to Send message:", err) } } }
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 newCmdClient(addr string) (mangos.Socket, error) { socket, err := req.NewSocket() if err != nil { return nil, err } if err := socket.SetOption(mangos.OptionSendDeadline, time.Second*3); err != nil { socket.Close() return nil, err } if err := socket.SetOption(mangos.OptionRecvDeadline, time.Second*3); err != nil { socket.Close() return nil, err } //socket.AddTransport(ipc.NewTransport()) socket.AddTransport(tcp.NewTransport()) if err := socket.Dial(addr); err != nil { socket.Close() return nil, err } return socket, nil }
func server(url string) { var sock mangos.Socket var err error var msg []byte if sock, err = surveyor.NewSocket(); err != nil { die("can't get new surveyor socket: %s", err) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Listen(url); err != nil { die("can't listen on surveyor socket: %s", err.Error()) } err = sock.SetOption(mangos.OptionSurveyTime, time.Second*2) if err != nil { die("SetOption(): %s", err.Error()) } for { fmt.Println("SERVER: SENDING DATE SURVEY REQUEST") if err = sock.Send([]byte("DATE")); err != nil { die("Failed sending survey: %s", err.Error()) } for { if msg, err = sock.Recv(); err != nil { break } fmt.Printf("SERVER: RECEIVED \"%s\" SURVEY RESPONSE\n", string(msg)) } } }
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 StartNanomsgJsonTest(address string, clients int, requestsPerClient int, messageSize int, timer metrics.Timer, requestSize *int) func(wg *sync.WaitGroup) { return func(wg *sync.WaitGroup) { var socket mangos.Socket var err error if socket, err = req.NewSocket(); err != nil { log.Fatal(err) } defer socket.Close() defer wg.Done() socket.AddTransport(tcp.NewTransport()) if err = socket.Dial("tcp://" + address); err != nil { log.Fatal(err) } request, _ := json.Marshal(Request{Method: "TEST", Payload: strings.Repeat("a", messageSize)}) *requestSize = len(request) for i := 0; i < requestsPerClient; i++ { timer.Time(func() { if err = socket.Send(request); err != nil { log.Fatal(err) } socket.Recv() }) } } }
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 testDevLoop(t *testing.T, addr string) { s1, err := pair.NewSocket() if err != nil { t.Errorf("Failed to open S1: %v", err) return } defer s1.Close() s1.AddTransport(tcp.NewTransport()) s1.AddTransport(ipc.NewTransport()) s1.AddTransport(inproc.NewTransport()) s1.AddTransport(tlstcp.NewTransport()) s1.AddTransport(ws.NewTransport()) s1.AddTransport(wss.NewTransport()) options := make(map[string]interface{}) if strings.HasPrefix(addr, "wss://") || strings.HasPrefix(addr, "tls+tcp://") { options[mangos.OptionTlsConfig] = srvCfg } if err := s1.ListenOptions(addr, options); err != nil { t.Errorf("Failed listening to %s: %v", addr, err) return } if err := mangos.Device(s1, s1); err != nil { t.Errorf("Device failed: %v", err) return } RunTests(t, addr, deviceCaseClient()) }
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 run(endpoint string, filter string, connect bool, ch chan *pubsub.Event) { sock, err := sub.NewSocket() if err != nil { log.Fatalln("sub.NewSocket error:", err) } sock.AddTransport(inproc.NewTransport()) sock.AddTransport(tcp.NewTransport()) defer sock.Close() if connect { err = sock.Dial(endpoint) } else { err = sock.Listen(endpoint) } if err != nil { log.Fatalln("sock connect failed:", err) } err = sock.SetOption(mangos.OptionSubscribe, []byte(filter)) if err != nil { log.Fatalln("sock SetOption failed:", err) } for { msg, e := sock.Recv() if e != nil { log.Fatal("error:", e) } event := ParseMsg(string(msg)) if event != nil { ch <- event } } }
func newEvtChannel(addr string) (mangos.Socket, error) { socket, err := sub.NewSocket() if err != nil { return nil, err } //if err := socket.SetOption(mangos.OptionRecvDeadline,time.Second * 30); err != nil { // socket.Close() // return nil,err //} //socket.AddTransport(ipc.NewTransport()) socket.AddTransport(tcp.NewTransport()) if err := socket.Dial(addr); err != nil { socket.Close() return nil, err } err = socket.SetOption(mangos.OptionSubscribe, []byte("")) if err != nil { return nil, err } return socket, nil }
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 }
// NewDaemon creates and returns a new Daemon from the provided Config. An // error is returned if the Daemon cannot be created. func NewDaemon(config *Config) (*Daemon, error) { rep, err := rep.NewSocket() if err != nil { return nil, err } rep.AddTransport(tcp.NewTransport()) return &Daemon{rep, nil, []*publisher{}, []*subscriber{}, config}, nil }
// AddTransports adds all known transports to the given socket. func AddTransports(sock mangos.Socket) { sock.AddTransport(tcp.NewTransport()) sock.AddTransport(inproc.NewTransport()) sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tlstcp.NewTransport()) sock.AddTransport(ws.NewTransport()) sock.AddTransport(wss.NewTransport()) }
func startNode(masterHost, name string) { var sock mangos.Socket var err error var msg []byte masterUrl := url.URL{Scheme: "tcp", Host: masterHost} ip := getPrivateIP() // Try to get new "respondent" socket if sock, err = respondent.NewSocket(); err != nil { utils.Die("Can't get new respondent socket: %s", err.Error()) } defer sock.Close() sock.AddTransport(tcp.NewTransport()) // Connect to master if err = sock.Dial(masterUrl.String()); err != nil { utils.Die("Can't dial on respondent socket: %s", err.Error()) } // Wait for a survey request and send responses for { if msg, err = sock.Recv(); err != nil { utils.Die("Cannot recv: %s", err.Error()) } fmt.Printf("Client(%s): Received \"%s\" survey request\n", name, string(msg)) var loadAvg *load.LoadAvgStat if loadAvg, err = load.LoadAvg(); err != nil { utils.Die("Cannot get load average: %s", err.Error()) } var cpuInfo []cpu.CPUInfoStat if cpuInfo, err = cpu.CPUInfo(); err != nil { utils.Die("Cannot get CPU info: %s", err.Error()) } fmt.Printf("CPU INFO len: %d\n", len(cpuInfo)) // Get the normalized CPU load avg := loadAvg.Load1 cores := int32(0) for _, info := range cpuInfo { fmt.Printf("Inner Cores: %d\n", info.Cores) cores += info.Cores } fmt.Printf("Load avg: %f\n", avg) fmt.Printf("Cores: %d\n", cores) avg = avg / float64(cores) fmt.Printf("Client(%s): Sending survey response\n", name) if err = sock.Send([]byte(fmt.Sprintf("%s,%f", ip, avg))); err != nil { utils.Die("Cannot send: %s", err.Error()) } } }
// NewClient creates and returns a new Client from the provided Benchmark // configuration. It returns an error if the Benchmark is not valid or it // can't communicate with any of the specified peers. func NewClient(b *Benchmark) (*Client, error) { if err := b.validate(); err != nil { return nil, err } brokerd, err := req.NewSocket() if err != nil { return nil, err } brokerd.AddTransport(tcp.NewTransport()) brokerd.SetOption(mangos.OptionSendDeadline, time.Duration(b.DaemonTimeout)*time.Second) brokerd.SetOption(mangos.OptionRecvDeadline, time.Duration(b.DaemonTimeout)*time.Second) if err := brokerd.Dial(fmt.Sprintf("tcp://%s", b.BrokerdHost)); err != nil { return nil, err } peerd := make(map[string]mangos.Socket, len(b.PeerHosts)) for _, peer := range b.PeerHosts { s, err := req.NewSocket() if err != nil { return nil, err } s.AddTransport(tcp.NewTransport()) s.SetOption(mangos.OptionSendDeadline, time.Duration(b.DaemonTimeout)*time.Second) s.SetOption(mangos.OptionRecvDeadline, time.Duration(b.DaemonTimeout)*time.Second) if err := s.Dial(fmt.Sprintf("tcp://%s", peer)); err != nil { return nil, err } peerd[peer] = s } return &Client{ brokerd: brokerd, peerd: peerd, Benchmark: b, }, nil }
func newSock() (mangos.Socket, error) { sock, err := pair.NewSocket() if err != nil { return nil, stackerr.Newf("can't get new pair socket: %s", err.Error()) } sock.AddTransport(tcp.NewTransport()) sock.AddTransport(tlstcp.NewTransport()) if err != nil { return nil, err } return sock, nil }
func testDevChain(t *testing.T, addr1 string, addr2 string, addr3 string) { // This tests using multiple devices across a few transports. // It looks like this: addr1->addr2->addr3 <==> addr3->addr2->addr1 var err error s := make([]mangos.Socket, 5) for i := 0; i < 5; i++ { if s[i], err = pair.NewSocket(); err != nil { t.Errorf("Failed to open S1_1: %v", err) return } defer s[i].Close() s[i].AddTransport(tcp.NewTransport()) s[i].AddTransport(inproc.NewTransport()) s[i].AddTransport(tlstcp.NewTransport()) s[i].AddTransport(ipc.NewTransport()) s[i].AddTransport(ws.NewTransport()) } if err = s[0].Listen(addr1); err != nil { t.Errorf("s[0] Listen: %v", err) return } if err = s[1].Dial(addr2); err != nil { t.Errorf("s[1] Dial: %v", err) return } if err = s[2].Listen(addr2); err != nil { t.Errorf("s[2] Listen: %v", err) return } if err = s[3].Dial(addr3); err != nil { t.Errorf("s[3] Dial: %v", err) return } if err = s[4].Listen(addr3); err != nil { t.Errorf("s[4] Listen: %v", err) return } if err = mangos.Device(s[0], s[1]); err != nil { t.Errorf("s[0],s[1] Device: %v", err) return } if err = mangos.Device(s[2], s[3]); err != nil { t.Errorf("s[2],s[3] Device: %v", err) return } if err = mangos.Device(s[4], nil); err != nil { t.Errorf("s[4] Device: %v", err) return } RunTests(t, addr1, deviceCaseClient()) }
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 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 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 starTestNewClient(t *testing.T, addr string, id int) *starTester { var err error bt := &starTester{id: id, rdoneq: make(chan bool), sdoneq: make(chan bool)} if bt.sock, err = star.NewSocket(); err != nil { t.Errorf("Failed getting client %d socket: %v", id, err) return nil } bt.sock.AddTransport(tcp.NewTransport()) if err = bt.sock.Dial(addr); err != nil { t.Errorf("Failed client %d dialing: %v", id, err) bt.sock.Close() return nil } return bt }
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 node0(url string) { var sock mangos.Socket var err error var msg []byte if sock, err = pull.NewSocket(); err != nil { die("can't get new pull socket: %s", err) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Listen(url); err != nil { die("can't listen on pull socket: %s", err.Error()) } for { // Could also use sock.RecvMsg to get header msg, err = sock.Recv() fmt.Printf("NODE0: RECEIVED \"%s\"\n", msg) } }
func main() { how_rand := flag.Bool("rand", false, "") flag.Parse() if flag.NArg() < 1 { log.Fatal("Missing arguments: at least one endpoint to bind to") } var err error var out mangos.Socket if out, err = push.NewSocket(); err != nil { log.Fatal("Nanomsg socket creation failure: ", err) } else { defer out.Close() out.AddTransport(ipc.NewTransport()) out.AddTransport(tcp.NewTransport()) out.SetOption(mangos.OptionWriteQLen, 16) out.SetOption(mangos.OptionRetryTime, 0) for i := 0; i < flag.NArg(); i++ { if err := out.Listen(flag.Arg(i)); err != nil { log.Fatal("Nanomsg listen() error: ", err) } } } switch { case *how_rand: Gen(out, func(tab []string) string { if len(tab) <= 0 { return "" } return tab[rand.Intn(len(tab))] }) default: i := 0 Gen(out, func(tab []string) string { if len(tab) <= 0 { return "" } i = (i + 1) % len(tab) return tab[i] }) } }