Esempio n. 1
0
        //
        //  Task worker
        //  Connects PULL socket to tcp://localhost:5557
        //  Collects workloads from ventilator via that socket
        //  Connects PUSH socket to tcp://localhost:5558
        //  Sends results to sink via that socket
        //
        public static void Start()
        {
            using (var context = new ZMQ.Context(1))
            {
                //  Socket to receive messages on
                var receiver = context.Socket(ZMQ.PULL);
                receiver.Connect("tcp://localhost:5557");

                //  Socket to send messages to
                var sender = context.Socket(ZMQ.PUSH);
                sender.Connect("tcp://localhost:5558");

                //  Process tasks forever
                while (true)
                {
                    byte[] bytes;
                    receiver.Recv(out bytes);
                    int milliseconds;
                    int.TryParse(Encoding.ASCII.GetString(bytes), out milliseconds);
                    //  Simple progress indicator for the viewer
                    Console.Write(new string('.', milliseconds / 10));

                    //  Do the work
                    System.Threading.Thread.Sleep(milliseconds);

                    //  Send results to sink
                    sender.Send(Encoding.ASCII.GetBytes(""));
                }
            }
        }
Esempio n. 2
0
        public void Run()
        {
            var inboundAddress = Configuration["inboundAddress"];
            if(String.IsNullOrWhiteSpace(inboundAddress))
                throw new InvalidOperationException("Configuration must contain an \"inboundAddress\" entry");

            Console.Title = String.Format("Worker Host - {0}", inboundAddress);

            var inboundHwm = Configuration.GetValue<ulong>("inboundHWM", 1000);

            using(var zmqContext = new ZMQ.Context())
            using(var inboundSocket = zmqContext.Socket(ZMQ.SocketType.PULL))
            {
                inboundSocket.HWM = inboundHwm;
                inboundSocket.Connect(inboundAddress);

                var workerContext = new WorkerContext(zmqContext, inboundSocket, Configuration);

                while(true)
                {
                    var workerType = inboundSocket.Recv<Type>();
                    Console.WriteLine("Creating a new instance of {0}", workerType.Name);
                    using(var worker = (IWorker)Activator.CreateInstance(workerType))
                        worker.MessageReceived(workerContext);
                }
            }
        }
Esempio n. 3
0
        static void Main(string[] args) {
            // allocate a buffer
            byte[] zmq_buffer = new byte[1024];

            //  Prepare our context and socket
            ZMQ.Context context = new ZMQ.Context(1);
            ZMQ.Socket  socket = context.Socket(ZMQ.REP);
            socket.Bind("tcp://*:5555");

            while (true) {
                try {
                    //  Wait for next request from client
                    socket.Recv(out zmq_buffer);
                    string request = Encoding.ASCII.GetString(zmq_buffer);

                    // log that we got one
                    Console.WriteLine("Received request: [%s]", request);

                    //  Do some 'work'
                    Thread.Sleep(1);

                    //  Send reply back to client
                    socket.Send(Encoding.ASCII.GetBytes("World".ToCharArray()));

                } catch (ZMQ.Exception z) {
                    // report the exception
                    Console.WriteLine("ZMQ Exception occurred : {0}", z.Message);
                }
            }
        }
Esempio n. 4
0
        public Socket CreateSocket(ZMQ.SocketType socketType)
        {
            var zmqsocket = _zeromqContext.Socket(socketType);
            var socket    = new Socket(this, zmqsocket);

            return(socket);
        }
Esempio n. 5
0
    static unsafe int Main(string[] args)
    {
        if (args.Length != 3)
        {
            Console.Out.WriteLine("usage: local_lat <address> " +
                "<message-size> <roundtrip-count>\n");
            return 1;
        }

        String address = args[0];
        uint messageSize = Convert.ToUInt32(args[1]);
        int roundtripCount = Convert.ToInt32(args[2]);

        //  Initialise 0MQ infrastructure
        ZMQ.Context ctx = new ZMQ.Context(1, 1, 0);
        ZMQ.Socket s = ctx.Socket(ZMQ.REP);
        s.Bind(address);

        //  Bounce the messages.
        for (int i = 0; i < roundtripCount; i++)
        {
            byte[] msg;
            s.Recv(out msg);
            Debug.Assert(msg.Length == messageSize);
            s.Send(msg);
        }

        System.Threading.Thread.Sleep(2000);

        return 0;
    }
        public bool StartNidsEvent()
        {
            if (string.IsNullOrEmpty(ServerAddr) || ServrtPort == 0)
            {
                Log(LOGLEVEL.ERROR, "incorrect server parameters!");
                return(false);
            }

            _context    = new ZMQ.Context(1);
            _subscriber = _context.Socket(ZMQ.SocketType.SUB);
            Connect();

            if (EventTags.Count == 0)
            {
                Log(LOGLEVEL.ERROR, "event node can not be 0!");
                return(false);
            }

            try
            {
                _event  = new ManualResetEvent(false);
                _thread = new Thread(EventRecvThreadMain)
                {
                    Name         = string.Format("nids_event_thread_{0}_{1}", ServerAddr, ServrtPort),
                    IsBackground = true
                };
                _thread.Start();
            }
            catch (Exception ex)
            {
                Log(LOGLEVEL.ERROR, ex.ToString());
                return(false);
            }
            return(true);
        }
Esempio n. 7
0
        //
        //  Task ventilator
        //  Binds PUSH socket to tcp://localhost:5557
        //  Sends batch of tasks to workers via that socket
        //
        static void Main()
        {
            using (var context = new ZMQ.Context(1))
            {
                //  Socket to send messages on
                var sender = context.Socket(ZMQ.PUSH);
                sender.Bind("tcp://*:5557");

                Console.WriteLine("Press Enter when the workers are ready: ");
                Console.ReadKey();
                Console.WriteLine("Sending tasks to workers...");

                //  The first message is "0" and signals start of batch
                sender.Send(Encoding.ASCII.GetBytes("0"));

                //  Initialize random number generator
                Random random = new Random();

                //  Send 100 tasks
                int total_msec = 0;     //  Total expected cost in msecs
                for (int task_nbr = 0; task_nbr < 100; task_nbr++) {
                    int workload;
                    //  Random workload from 1 to 100msecs
                    workload = random.Next(100) + 1;
                    total_msec += workload;
                    sender.Send(Encoding.ASCII.GetBytes(workload.ToString()));
                }

                Console.WriteLine("Total expected cost: {0} msec", total_msec);
                System.Threading.Thread.Sleep(1);  //  Give 0MQ time to deliver
            }
            Console.WriteLine("Hit a key to exit");
            Console.ReadKey();
        }
 static void Main(string[] args)
 {
     // allocate a buffer
     byte[] zmq_buffer = new byte[1024];
     //  Prepare our context and socket
     ZMQ.Context context = new ZMQ.Context(1);
     ZMQ.Socket  socket  = context.Socket(ZMQ.SocketType.REP);
     socket.Bind("tcp://*:5555");
     while (true)
     {
         try {
             //  Wait for next request from client
             zmq_buffer = socket.Recv();
             string request = Encoding.ASCII.GetString(zmq_buffer);
             // log that we got one
             Console.WriteLine("Received request: [%s]", request);
             //  Do some 'work'
             Thread.Sleep(1);
             //  Send reply back to client
             socket.Send(Encoding.ASCII.GetBytes("World".ToCharArray()));
         } catch (ZMQ.Exception z) {
             // report the exception
             Console.WriteLine("ZMQ Exception occurred : {0}", z.Message);
         }
     }
 }
Esempio n. 9
0
        public void Start()
        {
            if (IsListening) return;

            Messenger.Default.Send(new ZeroMqLogMessage() { Body = "Opening listener" });
            IsListening = true;

            try
            {
                using (var ctx = new ZMQ.Context(1))
                {

                    var socket = ctx.Socket(ZMQ.REP);
                    socket.Bind(_zeroMqAddress);

                    while (IsListening)
                    {
                        byte[] message;
                        socket.Recv(out message);
                        Messenger.Default.Send(new ZeroMqClientMessage());

                        socket.Send(Encoding.ASCII.GetBytes(""));
                    }
                }
            }
            catch (Exception e)
            {
                Messenger.Default.Send(new ZeroMqLogMessage() { Body = e.Message });
            }
        }
Esempio n. 10
0
        private Socket CreateSocket(ZMQ.SocketType socketType)
        {
            var zmqsocket = _context.Socket(socketType);
            var socket    = new Socket(zmqsocket);

            return(socket);
        }
Esempio n. 11
0
    static unsafe int Main(string[] args)
    {
        if (args.Length != 3)
        {
            Console.Out.WriteLine("usage: remote_thr <address> " +
                "<message-size> <message-count>\n");
            return 1;
        }

        String address = args[0];
        uint messageSize = Convert.ToUInt32(args[1]);
        int messageCount = Convert.ToInt32(args[2]);

        //  Initialise 0MQ infrastructure
        ZMQ.Context ctx = new ZMQ.Context(1, 1, 0);
        ZMQ.Socket s = ctx.Socket(ZMQ.PUB);
        s.Connect(address);

        //  Create a message to send.
        byte[] msg = new byte[messageSize];

        //  Start sending messages.
        for (int i = 0; i < messageCount; i++)
            s.Send(msg);

        System.Threading.Thread.Sleep(10000);

        return 0;
    }
Esempio n. 12
0
        static void Main(string[] args)
        {
            using (ZMQ.Context context = new ZMQ.Context(1))
            {
                using (ZMQ.Socket socket = context.Socket(ZMQ.SocketType.REP))
                {
                    socket.Bind("tcp://*:5555");
                    Console.WriteLine("Running server on port 5555");

                    while (true)
                    {
                        byte[] clientMessage = socket.Recv();
                        Console.WriteLine("Received {0} bytes", clientMessage.Length);

                        var ping = Wire.Deserialize<Ping>(clientMessage);
                        Console.WriteLine("From client: {0}", ping.ClientId);

                        Thread.Sleep(5000);

                        PingAck ack = new PingAck { TimeStamp = DateTime.UtcNow };
                        socket.Send(Wire.Serialize(ack));
                    }
                }
            }
        }
Esempio n. 13
0
        //
        //  Weather update client
        //  Connects SUB socket to tcp://localhost:5556
        //  Collects weather updates and finds avg temp in zipcode
        //
        public static void Main()
        {
            using (var context = new ZMQ.Context(1))
            {
                //  Socket to talk to server
                Console.WriteLine("Collecting updates from weather server...");
                var subscriber = context.Socket(ZMQ.SUB);
                subscriber.Connect("tcp://localhost:5556");

                //  Subscribe to zipcode NYC, 10001
                string filter = "10001";
                subscriber.SetSockOpt(ZMQ.SUBSCRIBE, filter);

                //  Process 100 updates
                int update_nbr;
                long total_temp = 0;
                for (update_nbr = 0; update_nbr < 100; update_nbr++)
                {
                    byte[] bytes;
                    subscriber.Recv(out bytes);
                    string astring = Encoding.ASCII.GetString(bytes);
                    string[] result = astring.Split(new char[] { ' ' });
                    int zipcode, temperature, relhumidity;
                    int.TryParse(result[0], out zipcode);
                    int.TryParse(result[1], out temperature);
                    int.TryParse(result[0], out relhumidity);
                    total_temp += temperature;
                }
                Console.WriteLine("Average temperature for zipcode {0} was {1}F", filter, total_temp / update_nbr);
            }
        }
Esempio n. 14
0
 static void Main(string[] args)
 {
     InitErrMessages();
     rep = cntx.Socket(ZMQ.SocketType.REP);
     rep.Bind("tcp://*:1000");
     pub = cntx.Socket(ZMQ.SocketType.PUB);
     pub.Bind("tcp://*:1001");
     while (true)
     {
         byte[] buf = rep.Recv(0);
         if (buf != null)
         {
             Process(buf);
         }
     }
 }
Esempio n. 15
0
        private void sendProc()
        {
            ZMQ.Socket resp = CTX.Socket(ZMQ.SocketType.PUB);
            if (!string.IsNullOrEmpty(SenderId))
            {
                resp.Identity = Encoding.ASCII.GetBytes(SenderId);
            }
            resp.Connect(pub_addr);

            while (isRunning)
            {
                itemsReadyToSend.WaitOne();
                lock (sendQ)
                {
                    while (sendQ.Count != 0)
                    {
                        byte[] stuffToSend = sendQ.Dequeue();

                        bool sentOk = false;
                        while (!sentOk)
                        {
                            try
                            {
                                resp.Send(stuffToSend);
                                sentOk = true;
                            }
                            catch (ZMQ.Exception ex)
                            {
                                if (ex.Errno == (int)ZMQ.ERRNOS.EAGAIN)
                                {
                                    sentOk = false;
                                }
                                else
                                {
                                    throw ex;
                                }
                            }
                        }
                    }
                }
            }

            resp.Dispose();
            itemsReadyToSend.Close();
            Interlocked.Decrement(ref threadStillRunning);
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            using(var zmqContext = new ZMQ.Context())
            using(var commandSocket = zmqContext.Socket(ZMQ.SocketType.PUSH))
            using(var resultSocket = zmqContext.Socket(ZMQ.SocketType.PULL))
            {
                commandSocket.HWM = 1;
                commandSocket.Connect(args[0]);

                resultSocket.HWM = 1;
                resultSocket.Bind(args[1]);

                while(true)
                {
                    Console.WriteLine("Enter a sequence of numbers and operators separated by spaces, e.g. 2 + 2:");
                    var command = Console.ReadLine();
                    if(command == "q")
                        break;

                    var tokens = command.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    var operators = tokens
                        .Where((s, i) => i % 2 == 1)
                        .Select(s => s
                            .Replace("+", "Retask.Calculator.Adder, Retask.Calculator")
                            .Replace("-", "Retask.Calculator.Subtractor, Retask.Calculator")
                            .Replace("*", "Retask.Calculator.Multiplier, Retask.Calculator")
                            .Replace("/", "Retask.Calculator.Divider, Retask.Calculator"))
                        .Select(s => Type.GetType(s, true, true));

                    var operands = tokens
                        .Where((s, i) => i % 2 == 0)
                        .Select(s => Int32.Parse(s));

                    commandSocket.SendMore(operators.First());
                    commandSocket.SendMore(new Queue<Type>(operators.Skip(1)));
                    commandSocket.SendMore(operands.First());
                    commandSocket.SendMore(new Queue<int>(operands.Skip(1)));
                    commandSocket.Send(args[1]);

                    var result = resultSocket.Recv<int>();
                    Console.WriteLine(" = {0}", result);
                }
            }
        }
Esempio n. 17
0
    static unsafe int Main(string[] args)
    {
        if (args.Length != 3)
        {
            Console.Out.WriteLine("usage: local_thr <address> " +
                "<message-size> <message-count>\n");
            return 1;
        }

        String address = args[0];
        uint messageSize = Convert.ToUInt32(args[1]);
        int messageCount = Convert.ToInt32(args[2]);

        //  Initialise 0MQ infrastructure
        ZMQ.Context ctx = new ZMQ.Context(1, 1, 0);
        ZMQ.Socket s = ctx.Socket(ZMQ.SUB);
        s.SetSockOpt(ZMQ.SUBSCRIBE, "");
        s.Bind(address);

        //  Wait for the first message.
        byte[] msg;
        s.Recv(out msg);
        Debug.Assert(msg.Length == messageSize);

        //  Start measuring time.
        System.Diagnostics.Stopwatch watch;
        watch = new Stopwatch();
        watch.Start();

        //  Receive all the remaining messages.
        for (int i = 1; i < messageCount; i++)
        {
            s.Recv(out msg);
            Debug.Assert(msg.Length == messageSize);
        }

        //  Stop measuring the time.
        watch.Stop();
        Int64 elapsedTime = watch.ElapsedTicks;

        // Compute and print out the throughput.
        Int64 messageThroughput = (Int64)(messageCount * Stopwatch.Frequency /
            elapsedTime);
        Int64 megabitThroughput = messageThroughput * messageSize * 8 /
            1000000;
        Console.Out.WriteLine("Your average throughput is {0} [msg/s]",
            messageThroughput.ToString());
        Console.Out.WriteLine("Your average throughput is {0} [Mb/s]",
            megabitThroughput.ToString());

        return 0;
    }
Esempio n. 18
0
        static void Main(string[] args)
        {
            // allocate a buffer
            byte[] zmq_buffer = new byte[1024];

            //  Prepare our context and socket
            ZMQ.Context context = new ZMQ.Context(1);
            ZMQ.Socket socket = context.Socket(ZMQ.REQ);
            socket.Connect("tcp://localhost:5555");

            string request = "";
            for (long requestNum = 0; requestNum != 10; requestNum++)
            {
                socket.Send(Encoding.ASCII.GetBytes("Hello".ToCharArray()));
                //  Wait for next request from client
                socket.Recv(out zmq_buffer);
                request = Encoding.ASCII.GetString(zmq_buffer);
           }
        }
Esempio n. 19
0
        //
        //  Task sink
        //  Binds PULL socket to tcp://localhost:5558
        //  Collects results from workers via that socket
        //
        static void Main(string[] args)
        {
            using (var context = new ZMQ.Context(1))
            {
                var receiver = context.Socket(ZMQ.PULL);
                receiver.Bind("tcp://*:5558");

                //  Wait for start of batch
                byte[] bytes;
                receiver.Recv(out bytes);

                //  Start our clock now
                DateTime tstart = DateTime.Now;
                Console.WriteLine(string.Format("Started at {0}", tstart.TimeOfDay));

                //  Process 100 confirmations
                for (int task_nbr = 0; task_nbr < 100; task_nbr++)
                {
                    receiver.Recv(out bytes);
                    if ((task_nbr / 10) * 10 == task_nbr)
                        Console.Write(":");
                    else
                        Console.Write(".");
                };
                Console.WriteLine();

                //  Calculate and report duration of batch
                DateTime tend = DateTime.Now;
                Console.WriteLine(string.Format("Ended at {0}", tend.TimeOfDay));
                TimeSpan tdiff = tend - tstart;
                Console.WriteLine();
                Console.WriteLine("Total elapsed time: {0} msec", tdiff.TotalMilliseconds);

                Console.WriteLine("Hit a key to exit");
                Console.ReadKey();
            }
        }
Esempio n. 20
0
        private void BtnZeroMqClick(object sender, RoutedEventArgs e)
        {
            Task.Factory.StartNew(() =>
                                      {
                                          using (var ctx = new ZMQ.Context(1))
                                          {
                                              var socket = ctx.Socket(ZMQ.REQ);
                                              socket.Connect(Settings.ZeroMqClientAddress);

                                              for (var i = 0; i < MessageCount; i++)
                                              {
                                                  socket.Send(Encoding.ASCII.GetBytes("Hello"));

                                                  byte[] message;
                                                  socket.Recv(out message);
                                              }
                                          }
                                      });
        }
Esempio n. 21
0
        private static void TestTransfer()
        {
            var watch = new Stopwatch();

            Console.WriteLine("Data Transfer Tests:");
            Console.WriteLine();
            Console.WriteLine("clrzmq:");

            var random = new Random();
            var data = new byte[1024];

            //First byte needs to be 0x00 for the subscription filter to work
            data[0] = 0x00;

            //Fill the array with some random data
            for (int i = 1; i < data.Length; i++)
                data[i] = (byte)random.Next(255);

            {
                Console.WriteLine("\tTest 1: Publish 1024 Byte payload 1,000,000 times, localhost TCP");

                var receiver = new BackgroundWorker();
                receiver.DoWork += (sender, e) =>
                    {
                        var receivedMessages = 0;

                        using (var context = new ZMQ.Context())
                        {
                            using (var socket = context.Socket(ZMQ.SocketType.SUB))
                            {
                                socket.Subscribe(new byte[] { 0x00 });

                                socket.Connect("tcp://127.0.0.1:12345");

                                for (int i = 0; i < (int)e.Argument; i++)
                                {
                                    var receivedData = socket.Recv();

                                    receivedMessages++;
                                }
                            }
                        }

                        e.Result = receivedMessages;
                    };

                var received = 0;

                receiver.RunWorkerCompleted += (sender, e) => { received = (int)e.Result; };

                var tries = 1000000;

                receiver.RunWorkerAsync(tries);

                watch.Start();

                using (var context = new ZMQ.Context())
                {
                    using (var socket = context.Socket(ZMQ.SocketType.PUB))
                    {
                        socket.Bind("tcp://127.0.0.1:12345");

                        for (int i = 0; i < tries; i++)
                            socket.Send(data);
                    }
                }

                EndTest(watch, tries, "Published command");

                Thread.Sleep(1);
                Console.WriteLine("\t\tReceived count: {0}", received);
            }

            {
                Console.WriteLine("\tTest 2: Req/Rep 1024 Byte payload 1,000,000 times, localhost TCP");

                var receiver = new BackgroundWorker();
                receiver.DoWork += (sender, e) =>
                {
                    var receivedMessages = 0;

                    using (var context = new ZMQ.Context())
                    {
                        using (var socket = context.Socket(ZMQ.SocketType.REP))
                        {
                            socket.Connect("tcp://127.0.0.1:12345");

                            for (int i = 0; i < (int)e.Argument; i++)
                            {
                                var receivedData = socket.Recv();

                                receivedMessages++;

                                socket.Send("Ok", Encoding.UTF8);
                            }
                        }
                    }

                    e.Result = receivedMessages;
                };

                var received = 0;

                receiver.RunWorkerCompleted += (sender, e) => { received = (int)e.Result; };

                var tries = 1000000;

                receiver.RunWorkerAsync(tries);

                watch.Start();

                using (var context = new ZMQ.Context())
                {
                    using (var socket = context.Socket(ZMQ.SocketType.REQ))
                    {
                        socket.Bind("tcp://127.0.0.1:12345");

                        for (int i = 0; i < tries; i++)
                        {
                            socket.Send(data);

                            var response = socket.Recv();
                        }
                    }
                }

                EndTest(watch, tries, "Sent command");

                Thread.Sleep(1);
                Console.WriteLine("\t\tReceived count: {0}", received);
            }

            {
                Console.WriteLine("\tTest 3: Router/Dealer 1024 Byte payload 1,000,000 times, localhost TCP");

                var received = 0;

                var receiver = new BackgroundWorker();

                receiver.DoWork += (sender, e) =>
                {
                    using (var context = new ZMQ.Context())
                    {
                        using (var client = context.Socket(ZMQ.SocketType.ROUTER))
                        {
                            client.Connect("tcp://127.0.0.1:23456");

                            var pollItem = client.CreatePollItem(ZMQ.IOMultiPlex.POLLIN);

                            pollItem.PollInHandler += (socket, revents) =>
                                {
                                    var receivedData = socket.Recv();

                                    if(receivedData != null)
                                        received++;

                                    //Respond
                                    socket.Send("OK", Encoding.UTF8);
                                };

                            var items = new[] {pollItem};

                            while (true)
                            {
                                context.Poll(items, 100);
                            }
                        }
                    }

                };

                var tries = 1000000;

                receiver.RunWorkerAsync();

                watch.Start();

                using (var context = new ZMQ.Context())
                {
                    using (var server = context.Socket(ZMQ.SocketType.DEALER))
                    {
                        server.Bind("tcp://127.0.0.1:23456");

                        for (int i = 0; i < tries; i++)
                        {
                            server.Send(data);
                        }
                    }
                }

                var elapsedMSToSend = watch.ElapsedMilliseconds;

                Console.WriteLine("\t\tSent {0} commands in {1:0.0000} ms", tries, elapsedMSToSend);

                while (received < tries)
                    Thread.Sleep(10);

                Console.WriteLine("\t\tReceived count: {0}", received);

                watch.Stop();
                Console.WriteLine("\t\tAll responses processed in {0:0.0000} ms", watch.ElapsedMilliseconds);
            }
        }
Esempio n. 22
0
        private void ZMQConnect()
        {
            //  Prepare our context and socket
            m_Context= new ZMQ.Context(1);

            m_Socket = m_Context.Socket(ZMQ.XREQ);
            m_Socket.Connect("tcp://localhost:5555");
        }