Esempio n. 1
0
 protected override void DoServer(NetMQSocket socket, int messageSize)
 {
     for (int i = 0; i < Iterations; i++)
     {
         byte[] message = socket.Receive();
         socket.Send(message);
     }
 }
Esempio n. 2
0
        protected override long DoClient(NetMQSocket socket, int messageSize)
        {
            var msg = new byte[messageSize];

            var watch = Stopwatch.StartNew();

            for (int i = 0; i < Iterations; i++)
            {
                socket.Send(msg);
                socket.Receive(); // ignore response
            }

            return watch.ElapsedTicks;
        }
Esempio n. 3
0
        public void Ipv6ToIpv4()
        {
            using (var context = NetMQContext.Create())
                using (var localDealer = context.CreateDealerSocket())
                    using (NetMQSocket connectingDealer = context.CreateDealerSocket())
                    {
                        localDealer.Options.IPv4Only = false;
                        var port = localDealer.BindRandomPort(string.Format("tcp://*"));

                        connectingDealer.Connect(string.Format("tcp://{0}:{1}", IPAddress.Loopback, port));

                        connectingDealer.Send("test");

                        Assert.AreEqual("test", localDealer.ReceiveFrameString());
                    }
        }
Esempio n. 4
0
        protected override void DoClient(int id, NetMQSocket socket)
        {
            const string value    = "Hello World";
            var          expected = value + " " + id;

            Console.WriteLine("Client: {0} sending: {1}", id, expected);
            socket.Send(expected);

            Thread.Sleep(Random.Next(1, 50));

            var response = socket.ReceiveStringMessages().ToList();

            Assert.AreEqual(1, response.Count);
            Assert.AreEqual(expected, response[0]);
            Console.WriteLine("Client: {0} received: {1}", id, response[0]);
        }
Esempio n. 5
0
        private void Send(string objCode, data.TechCycle cycle)
        {
            string msg = JsonConvert.SerializeObject(new IndexTask
            {
                type  = ObjectType.Object,
                code  = objCode,
                cycle = cycle
            });

            byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
            _socket.Send(msg);
            this.Log().Info("发送:{" + msg + "}");
            string message = _socket.ReceiveString();

            this.Log().Info("接收:" + message);
        }
Esempio n. 6
0
        protected override void DoWork(NetMQSocket socket)
        {
            var received = socket.ReceiveStringMessages().ToList();

            for (var i = 0; i < received.Count; i++)
            {
                if (i == received.Count - 1)
                {
                    socket.Send(received[i]);
                }
                else
                {
                    socket.SendMore(received[i]);
                }
            }
        }
Esempio n. 7
0
        private static bool TryRequest(NetMQContext context, string endpoint, string requestString)
        {
            Console.WriteLine("Trying echo service at {0}", endpoint);
            NetMQSocket client = context.CreateRequestSocket();

            client.Options.Linger = TimeSpan.Zero;
            client.Connect(endpoint);
            client.Send(requestString);
            client.ReceiveReady += ClientOnReceiveReady;
            bool pollResult = client.Poll(TimeSpan.FromMilliseconds(REQUEST_TIMEOUT));

            client.ReceiveReady -= ClientOnReceiveReady;
            client.Disconnect(endpoint);
            client.Dispose();

            return(pollResult);
        }
Esempio n. 8
0
        public void Send(PushMsg msg)
        {
            if (_disposeCount != 0)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }

            try
            {
                _socket.Send(msg.SerializeMessage());
            }
            catch (TerminatingException)
            {
                Debug.WriteLine(string.Format("TerminatingException: auto-disposing {0}...", this.GetType().Name));
                ((IDisposable)this).Dispose();
                throw;
            }
        }
Esempio n. 9
0
        public void Issue52_ReqToRouterBug()
        {
            using (var ctx = NetMQContext.Create())
            {
                using (NetMQSocket router = ctx.CreateRouterSocket(), req = ctx.CreateRequestSocket())
                {
                    router.Bind("inproc://example");
                    req.Connect("inproc://example");

                    string testmessage = "Simple Messaging Test";
                    req.Send(testmessage);

                    var msg = router.ReceiveMessage();
                    Assert.AreEqual(3, msg.FrameCount);
                    Assert.AreEqual(msg[2].ConvertToString(), testmessage);
                }
            }
        }
        private void SendEvents(String submissionUri, CancellationToken cancellationToken)
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket pushSocket = context.CreatePushSocket())
                {
                    pushSocket.IgnoreErrors = true;
                    pushSocket.Connect(submissionUri);

                    Logger.Info("ZeroMQCache: Connected to submissionUri \"{0}\".", submissionUri);

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        try
                        {
                            ZeroMQMessage message;

                            if (mQueue.TryTake(out message, TimeSpan.FromSeconds(1)))
                            {
                                Logger.Debug("ZeroMQCache: Sending -> {0}", message.ToString());

                                pushSocket.SendMore(message.Topic);
                                pushSocket.SendMore(message.Client);
                                pushSocket.Send(message.Content);
                            }
                        }
                        catch (OperationCanceledException)
                        {
                            // We have been asked to cancel operation
                            break;
                        }
                        catch (Exception ex)
                        {
                            Logger.Error("ZeroMQCache: Error sending message.", ex);
                        }
                    }

                    // Close socket
                    pushSocket.Close();
                }

                context.Terminate();
            }
        }
Esempio n. 11
0
        public void BindRandom()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket randomDealer = context.CreateDealerSocket())
                {
                    int port = randomDealer.BindRandomPort("tcp://*");

                    using (NetMQSocket connectingDealer = context.CreateDealerSocket())
                    {
                        connectingDealer.Connect("tcp://127.0.0.1:" + port);

                        randomDealer.Send("test");

                        Assert.AreEqual("test", connectingDealer.ReceiveString());
                    }
                }
            }
        }
Esempio n. 12
0
        public void Ipv6ToIpv4()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket localDealer = context.CreateDealerSocket())
                {
                    localDealer.Options.IPv4Only = false;
                    localDealer.Bind(string.Format("tcp://*:5002"));
                    using (NetMQSocket connectingDealer = context.CreateDealerSocket())
                    {
                        connectingDealer.Connect("tcp://" + IPAddress.Loopback.ToString() + ":5002");

                        connectingDealer.Send("test");

                        Assert.AreEqual("test", localDealer.ReceiveString());
                    }
                }
            }
        }
Esempio n. 13
0
            public ResponseMsg Send(RequestMsg msg)
            {
                if (_disposeCount != 0)
                {
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                try
                {
                    _socket.Send(msg.SerializeMessage());
                    return(_socket.Receive().DeserializeMessage() as ResponseMsg);
                }
                catch (TerminatingException)
                {
                    Debug.WriteLine(string.Format("TerminatingException: auto-disposing {0} ({1:x})...", this.GetType().Name, this.GetHashCode()));
                    ((IDisposable)this).Dispose();
                    throw;
                }
            }
Esempio n. 14
0
        private static void RelayMessage(NetMQSocket source, NetMQSocket destination)
        {
            bool hasMore = true;

            while (hasMore)
            {
                // side effect warning!
                // note! that this uses Receive mode that gets a byte[], the router c# implementation
                // doesnt work if you get a string message instead of the byte[] i would prefer the solution thats commented.
                // but the router doesnt seem to be able to handle the response back to the client
                //string message = source.Receive(Encoding.Unicode);
                //hasMore = source.RcvMore;
                //destination.Send(message, Encoding.Unicode, hasMore ? SendRecvOpt.SNDMORE : SendRecvOpt.NONE);

                //int bytesReceived;
                byte[] message = source.Receive(true, out hasMore);
                //hasMore = source.ReceiveMore;
                destination.Send(message, message.Length, hasMore ? SendReceiveOptions.SendMore : SendReceiveOptions.None);
            }
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket response = context.CreateResponseSocket())
                {
                    string address = GetComputerLanIP();

                    if (!string.IsNullOrEmpty(address))
                    {
                        Console.WriteLine("Binding tcp://{0}:{1}", address, PORT_NUMBER);
                        response.Bind(string.Format("tcp://{0}:{1}", address, PORT_NUMBER));

                        while (true)
                        {
                            bool   hasMore = true;
                            string msg     = response.ReceiveString(out hasMore);
                            if (string.IsNullOrEmpty(msg))
                            {
                                Console.WriteLine("No msg received.");
                                break;
                            }

                            Console.WriteLine("Msg received! {0}", msg);
                            response.Send(msg, false, hasMore);

                            Thread.Sleep(1000);
                        }

                        response.Options.Linger = TimeSpan.Zero;
                    }
                    else
                    {
                        Console.WriteLine("Wrong IP address");
                    }

                    Console.WriteLine("Press ENTER to exit...");
                    Console.ReadLine();
                }
            }
        }
Esempio n. 16
0
        private static void RepOnReceiveReady(object sender, NetMQSocketEventArgs args)
        {
            try
            {
                NetMQSocket rep = args.Socket;

                byte[] message = rep.ReceiveFrameBytes();

                //Thread.Sleep(1000); //  Simulate 'work'

                byte[] response =
                    Encoding.Unicode.GetBytes(Encoding.Unicode.GetString(message) + " World from worker " + Encoding.Unicode.GetString(rep.Options.Identity));

                rep.Send(response, response.Length, SendReceiveOptions.DontWait);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception on RepOnReceiveReady: {0}", ex.Message);
                throw;
            }
        }
Esempio n. 17
0
        public static void Server(NetMQContext context)
        {
            using (NetMQSocket serverSocket = context.CreateResponseSocket())
            {
                JavaScriptSerializer seriallizer = null;
                serverSocket.Bind("tcp://127.0.0.1:5555");
                while (true)
                {
                    seriallizer = new JavaScriptSerializer();
                    var msg = serverSocket.ReceiveFrameBytes();


                    Console.WriteLine("Receive message {0}", Common.ByteConvertHelp.Bytes2Object(msg));
                    serverSocket.Send("Send Hello world");
                    if (Common.ByteConvertHelp.Bytes2Object(msg) == "exit")
                    {
                        break;
                    }
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Create a new instance of a Proxy (NetMQ.Proxy)
        /// with the given sockets to serve as a front-end, a back-end, and a control socket.
        /// </summary>
        /// <param name="publisherAddress">the address that messages will be forwarded from</param>
        /// <param name="subscriberAddress">the address that messages should be sent to</param>
        /// <param name="heartbeat">the timespan at which to send HEARTBEAT messages (in milliseconds) - you can set this to zero if not needed</param>
        /// <param name="control">this socket will have messages also sent to it - you can set this to null if not needed</param>
        public ZeroMqHub(string publisherAddress, string subscriberAddress, int heartbeat = 0, NetMQSocket control = null)
        {
            _subscriberAddress = subscriberAddress;
            _publisherAddress = publisherAddress;
            var context = NetMQContext.Create();
            _subscriber = context.CreateXSubscriberSocket();
            _publisher = context.CreateXPublisherSocket();
            _control = control;

            if (heartbeat > 0)
            {
                _heartbeat = new NetMQTimer(heartbeat);
                _heartbeat.Elapsed += (s, a) => _publisher.Send("HEARTBEAT");
            }

            Name = "XPub-XSub";
            PSJobTypeName = typeof(ZeroMqHub).Name;

            _subscriber.Bind(subscriberAddress);
            _publisher.Bind(publisherAddress);
        }
Esempio n. 19
0
 private byte[] Send(byte[] request)
 {
     try
     {
         //SendStatus result =
         _socket.Send(request);
         //if (result != SendStatus.Sent)
         //    throw new Exception("Error sending message on socket");
         NetMQMessage msg = _socket.ReceiveMessage(); //TODO:TimeSpan.FromSeconds(5)
         if (msg.IsEmpty)
         {
             return(new byte[0]);
         }
         return(msg[0].Buffer);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         return(new byte[0]);
     }
 }
Esempio n. 20
0
        private void RepReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            NetMQSocket socket = e.Socket;
            bool        hasMore;

            try
            {
                string msg = Encoding.UTF8.GetString(socket.Receive(SendReceiveOptions.DontWait, out hasMore));
                if (msg.Length > 0)
                {
                    string resp = reqMsgHandler(msg);
                    byte[] data = Encoding.UTF8.GetBytes(resp);
                    socket.Send(data, data.Length);
                }
            }
            catch (Exception ce)
            {
                Console.WriteLine("OnResponse Error: {0}", ce.Message);
                log.Error("Response Message error: ", ce);
            }
        }
Esempio n. 21
0
        public void HasInTest()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket server = context.CreateRouterSocket())
                {
                    server.Bind("tcp://*:5557");

                    // no one sent a message so it should be fasle
                    Assert.IsFalse(server.HasIn);

                    using (NetMQSocket client = context.CreateDealerSocket())
                    {
                        client.Connect("tcp://localhost:5557");

                        // wait for the client to connect
                        Thread.Sleep(100);

                        // now we have one client connected but didn't send a message yet
                        Assert.IsFalse(server.HasIn);

                        client.Send("1");

                        // wait for the message to arrive
                        Thread.Sleep(100);

                        // the has in should indicate a message is ready
                        Assert.IsTrue(server.HasIn);

                        byte[] identity = server.Receive();
                        string message  = server.ReceiveString();

                        Assert.AreEqual(message, "1");

                        // we read the message, it should false again
                        Assert.IsFalse(server.HasIn);
                    }
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        ///     Handles requests for information on data that is available in local storage
        /// </summary>
        private void AcceptAvailableDataRequest(string requesterIdentity)
        {
            lock (_socketLock)
            {
                if (_socket != null)
                {
                    using (var ms = new MemoryStream())
                    {
                        // Get the instrument
                        bool hasMore;
                        var  buffer     = _socket.ReceiveFrameBytes(out hasMore);
                        var  instrument = MyUtils.ProtoBufDeserialize <Instrument>(buffer, ms);

                        _logger.Info($"Received local data storage info request for {instrument.Symbol}.");
                        // And send the reply
                        var storageInfo = _broker.GetAvailableDataInfo(instrument);

                        _socket.SendMoreFrame(requesterIdentity);
                        _socket.SendMoreFrame(MessageType.AvailableDataReply);
                        _socket.SendMoreFrame(MyUtils.ProtoBufSerialize(instrument, ms));
                        _socket.SendMoreFrame(BitConverter.GetBytes(storageInfo.Count));

                        for (int i = 0; i < storageInfo.Count; i++)
                        {
                            var sdi = storageInfo[i];
                            if (i < storageInfo.Count - 1)
                            {
                                _socket.SendMoreFrame(MyUtils.ProtoBufSerialize(sdi, ms));
                            }
                            else
                            {
                                _socket.SendFrame(MyUtils.ProtoBufSerialize(sdi, ms));
                            }
                        }
                        _socket.Send("END");
                    }
                }
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Create a new instance of a Proxy (NetMQ.Proxy)
        /// with the given sockets to serve as a front-end, a back-end, and a control socket.
        /// </summary>
        /// <param name="publisherAddress">the address that messages will be forwarded from</param>
        /// <param name="subscriberAddress">the address that messages should be sent to</param>
        /// <param name="heartbeat">the timespan at which to send HEARTBEAT messages (in milliseconds) - you can set this to zero if not needed</param>
        /// <param name="control">this socket will have messages also sent to it - you can set this to null if not needed</param>
        public ZeroMqHub(string publisherAddress, string subscriberAddress, int heartbeat = 0, NetMQSocket control = null)
        {
            _subscriberAddress = subscriberAddress;
            _publisherAddress  = publisherAddress;
            var context = NetMQContext.Create();

            _subscriber = context.CreateXSubscriberSocket();
            _publisher  = context.CreateXPublisherSocket();
            _control    = control;

            if (heartbeat > 0)
            {
                _heartbeat          = new NetMQTimer(heartbeat);
                _heartbeat.Elapsed += (s, a) => _publisher.Send("HEARTBEAT");
            }

            Name          = "XPub-XSub";
            PSJobTypeName = typeof(ZeroMqHub).Name;

            _subscriber.Bind(subscriberAddress);
            _publisher.Bind(publisherAddress);
        }
Esempio n. 24
0
        /// <summary>
        /// Add an instrument to QDMS.
        /// </summary>
        /// <param name="instrument"></param>
        /// <returns>The instrument with its ID set if successful, null otherwise.</returns>
        public Instrument AddInstrument(Instrument instrument)
        {
            if (!Connected)
            {
                RaiseEvent(Error, this, new ErrorArgs(-1, "Could not add instrument - not connected."));
                return(null);
            }

            if (instrument == null)
            {
                RaiseEvent(Error, this, new ErrorArgs(-1, "Could not add instrument - instrument is null."));
                return(null);
            }

            using (NetMQSocket s = _context.CreateSocket(ZmqSocketType.Req))
            {
                s.Connect(string.Format("tcp://{0}:{1}", _host, _instrumentServerPort));
                var ms = new MemoryStream();

                s.SendMore("ADD"); //first we send an "ADD" request

                //then we need to serialize and send the instrument
                s.Send(MyUtils.ProtoBufSerialize(instrument, ms));

                //then get the reply
                string result = s.ReceiveString(TimeSpan.FromSeconds(1));

                if (result != "SUCCESS")
                {
                    RaiseEvent(Error, this, new ErrorArgs(-1, "Instrument addition failed: received no reply."));
                    return(null);
                }

                //Addition was successful, receive the instrument and return it
                byte[] serializedInstrument = s.Receive();

                return(MyUtils.ProtoBufDeserialize <Instrument>(serializedInstrument, ms));
            }
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            using (var context = NetMQContext.Create())
            {
                worker = context.CreateRequestSocket();

                var randomizer = new Random(DateTime.Now.Millisecond);
                Guid guid = Guid.NewGuid();
                worker.Options.Identity = Encoding.Unicode.GetBytes(guid.ToString());
                worker.ReceiveReady += WorkerOnReceiveReady;
                worker.Connect(SERVER_ENDPOINT);

                Console.WriteLine("W: {0} worker ready", guid);
                worker.Send(Encoding.Unicode.GetBytes(LRU_READY));

                var cycles = 0;
                while (true)
                {
                    cycles += 1;
                    if (cycles > 3 && randomizer.Next(0, 5) == 0)
                    {
                        Console.WriteLine("W: {0} simulating a crash", guid);
                        System.Threading.Thread.Sleep(5000);
                        //break;
                    }
                    else if (cycles > 3 && randomizer.Next(0, 5) == 0)
                    {
                        Console.WriteLine("W: {0} simulating CPU overload", guid);
                        System.Threading.Thread.Sleep(3000);
                    }
                    Console.WriteLine("W: {0} normal reply", guid);

                    worker.Poll(TimeSpan.FromMilliseconds(1000));
                }

            }
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            using (var context = NetMQContext.Create())
            {
                worker = context.CreateRequestSocket();

                var  randomizer = new Random(DateTime.Now.Millisecond);
                Guid guid       = Guid.NewGuid();
                worker.Options.Identity = Encoding.Unicode.GetBytes(guid.ToString());
                worker.ReceiveReady    += WorkerOnReceiveReady;
                worker.Connect(SERVER_ENDPOINT);

                Console.WriteLine("W: {0} worker ready", guid);
                worker.Send(Encoding.Unicode.GetBytes(LRU_READY));

                var cycles = 0;
                while (true)
                {
                    cycles += 1;
                    if (cycles > 3 && randomizer.Next(0, 5) == 0)
                    {
                        Console.WriteLine("W: {0} simulating a crash", guid);
                        System.Threading.Thread.Sleep(5000);
                        //break;
                    }
                    else if (cycles > 3 && randomizer.Next(0, 5) == 0)
                    {
                        Console.WriteLine("W: {0} simulating CPU overload", guid);
                        System.Threading.Thread.Sleep(3000);
                    }
                    Console.WriteLine("W: {0} normal reply", guid);

                    worker.Poll(TimeSpan.FromMilliseconds(1000));
                }
            }
        }
Esempio n. 27
0
        private static IList<BehaviorInfo> GetBehaviorModules2(NetMQSocket socket,
            IList<BehaviorInfo> behaviorList)
        {
            var ret = new List<BehaviorInfo>();
            var dict = new Dictionary<string, BehaviorInfo>();
            //behavior_modules
            if (socket != null && behaviorList != null && behaviorList.Count > 0)
            {
                socket.Send("behavior_modules");
                var resp = socket.ReceiveString(new TimeSpan(0, 0, 0, 0, RecvTimeout));
                if (!string.IsNullOrEmpty(resp))
                {
                    var modules = JArray.Parse(resp);
                    if (modules != null && modules.Count > 0)
                    {
                        //Console.WriteLine(resp);
                        foreach (var module in modules)
                        {
                            var moduleName = module.Value<string>("name");
                            var responder = module.SelectToken("$.responder");
                            string host = string.Empty;
                            int port = 0;
                            if (responder != null)
                            {
                                host = responder.Value<string>("Host");
                                port = responder.Value<int>("Port");
                            }
                            var behaviors = module.SelectToken("$.behaviors");
                            foreach (var behavior in behaviors)
                            {
                                string name = behavior.Value<string>("name");
                                string functionName = behavior.Value<string>("function_name");
                                var parameters = new Dictionary<string, object>();
                                var args = behavior.SelectToken("$.arg");
                                foreach (var arg in args)
                                {
                                    parameters.Add(arg.Value<string>("name"), new Dictionary<string, object>
                                    {
                                        {"value", arg.Value<string>("value")},
                                        {"place_holder", arg.Value<string>("place_holder")},
                                        {"type", arg.Value<string>("type")}
                                    });
                                }
                                if (!dict.ContainsKey(name))
                                {
                                    dict.Add(name, new BehaviorInfo
                                    {
                                        BehaviorName = name,
                                        FunctionName = functionName,
                                        Ip = host,
                                        Port = port,
                                        Parameters = parameters
                                    });
                                }
                            }
                        }
                    }
                }
                if (dict.Count > 0)
                {

                    // ReSharper disable once LoopCanBeConvertedToQuery
                    foreach (var item in behaviorList)
                    {
                        Log.InfoFormat("Before : {0}",item.ToString());
                        if (dict.ContainsKey(item.BehaviorName))
                        {
                            var temp = dict[item.BehaviorName].Clone() as BehaviorInfo;
                            if (temp != null)
                            {
                                foreach (var parameter in item.Parameters)
                                {
                                    if (!temp.Parameters.ContainsKey(parameter.Key))
                                    {
                                        temp.Parameters.Add(parameter);
                                    }
                                    else
                                    {
                                        temp.Parameters[parameter.Key] = parameter.Value;
                                    }
                                }
                                Log.InfoFormat("After : {0}", temp.ToString());
                                ret.Add(temp);
                            }

                            //ret.Add(dict[item.BehaviorName]);
                            // Update the values of the parameter list with the once originally parsed from the xml file
                            //foreach (var parameter in item.Parameters)
                            //{
                            //    if (!dict[item.BehaviorName].Parameters.ContainsKey(parameter.Key))
                            //    {
                            //        dict[item.BehaviorName].Parameters.Add(parameter);
                            //    }
                            //    else
                            //    {
                            //        dict[item.BehaviorName].Parameters[parameter.Key] = parameter.Value;
                            //    }
                            //}
                            //ret.Add(dict[item.BehaviorName]);
                        }
                    }
                }
            }
            return ret;
        }
Esempio n. 28
0
        public void OnDataReady()
        {
            switch (m_state)
            {
            case WebSocketClientState.Closed:
                m_state = WebSocketClientState.Handshake;
                string clientHandshake = m_streamSocket.ReceiveString();

                string[] lines = clientHandshake.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                string key;

                if (ValidateClientHandshake(lines, out key))
                {
                    string acceptKey = GenerateAcceptKey(key);

                    try
                    {
                        m_streamSocket.SendMore(Identity, Identity.Length, true);
                        m_streamSocket.Send("HTTP/1.1 101 Switching Protocols\r\n" +
                                            "Upgrade: websocket\r\n" +
                                            "Connection: Upgrade\r\n" +
                                            "Sec-WebSocket-Accept: " + acceptKey + "\r\n" +
                                            "Sec-WebSocket-Protocol: WSNetMQ\r\n\r\n");

                        m_decoder          = new Decoder();
                        m_decoder.Message += OnMessage;
                        m_state            = WebSocketClientState.Ready;
                    }
                    catch (NetMQException)
                    {
                        m_state = WebSocketClientState.Closed;
                    }
                }
                else
                {
                    m_state = WebSocketClientState.Closed;

                    try
                    {
                        m_streamSocket.SendMore(Identity, Identity.Length, true);
                        m_streamSocket.Send("HTTP/1.1 400 Bad Request\r\nSec-WebSocket-Version: 13\r\n");

                        // invalid request, close the socket and raise closed event
                        m_streamSocket.SendMore(Identity, Identity.Length, true);
                        m_streamSocket.Send("");
                    }
                    catch (NetMQException ex)
                    {
                    }
                }

                break;

            case WebSocketClientState.Ready:
                byte[] message = m_streamSocket.Receive();
                m_decoder.Process(message);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
    // Update is called once per frame
    //
    void Update()
    {
        AsyncIO.ForceDotNet.Force();
        string top;
        string message;

        if (client.TryReceiveFrameString(out top))
        {
            if (client.TryReceiveFrameString(out message))
            {
                Debug.Log(message);
                string[] coord = message.Split();
                transX     = int.Parse(coord [0]);
                transY     = int.Parse(coord [1]);
                calibrated = true;
            }
        }
        if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.JoystickButton0))
        {
            calCount++;
            textTime = 5.0f;
            if (calCount != 1)
            {
                calibrator.Send("Calibrate");
            }
            else
            {
                calibrated   = false;
                trackingMode = 0;
                targetPrefab.SetActive(false);
            }
            if (calCount == 10)
            {
                calibrated = true;
                targetPrefab.SetActive(true);
                uiText.text  = "Press A to recalibrate" + Environment.NewLine + "Press B to toggle eye tracking modes";
                textTime     = 0.0f;
                trackingMode = 1;
            }
        }
        if (Input.GetKeyDown(KeyCode.C) || Input.GetKeyDown(KeyCode.JoystickButton1))
        {
            if (calibrated)
            {
                if (trackingMode == 0)
                {
                    targetPrefab.SetActive(true);
                }
                if (trackingMode > 0)
                {
                    targetPrefab.SetActive(false);
                }
                trackingMode = (trackingMode + 1) % 3;
            }
            else if (calCount == 0)
            {
                //change gui
                uiText.text = "Press A to begin calibration";
                textTime    = 0.0f;
            }
        }

        if (calCount != curCount)
        {
            calCount = calCount % 10;
            curCount = calCount;

            gameObject.GetComponent <Image> ().sprite = calImages [calCount];
        }
        if (trackingMode == 0 && calibrated)
        {
            gameObject.GetComponent <Image> ().sprite = calImages [0];
        }
        if (trackingMode == 1)
        {
            tr  = GameObject.FindGameObjectWithTag("MainCamera").transform;
            vec = (tr.forward) + (tr.right * ((transX - 590) / 1000)) + (tr.up * (((-transY) + 282) / 1000));
            //vec = (tr.forward) + (tr.right * (transX)) + (tr.up * ((transY)));
            Vector3    orig = GameObject.FindGameObjectWithTag("MainCamera").transform.position;
            RaycastHit hit;
            Ray        ray = new Ray(orig, vec);
            //Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit, 100.0f))
            {
                //Debug.DrawLine (ray.origin, hit.point);
                targetPrefab.transform.position = hit.point;
                targetPrefab.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
                targetPrefab.SetActive(true);
            }
            else
            {
                targetPrefab.SetActive(false);
            }
        }
        else if (trackingMode == 2)
        {
            int sectionIndex = 0;
            if (transX > 368)
            {
                sectionIndex++;
                if (transX > 810)
                {
                    sectionIndex++;
                }
            }
            if (transY > 163)
            {
                sectionIndex += 3;
                if (transY > 400)
                {
                    sectionIndex += 3;
                }
            }
            gameObject.GetComponent <Image> ().sprite = secImages [sectionIndex];
        }
        if (textTime >= 2.0)
        {
            uiText.text = "";
        }
        else
        {
            textTime += Time.deltaTime;
        }
    }
Esempio n. 30
0
        protected override long DoClient(NetMQSocket socket, int messageSize)
        {
            var msg = new Msg();
            msg.InitGC(new byte[messageSize], messageSize);

            var watch = Stopwatch.StartNew();

            for (int i = 0; i < Iterations; i++)
            {
                socket.Send(ref msg, SendReceiveOptions.None);
                socket.Receive(ref msg, SendReceiveOptions.None);
            }

            return watch.ElapsedTicks;
        }
Esempio n. 31
0
 private static IList<BehaviorInfo> GetBehaviorModules(NetMQSocket socket,
     IList<BehaviorInfo> behaviorList)
 {
     var ret = new List<BehaviorInfo>();
     var dict = new Dictionary<string, BehaviorInfo>();
     //behavior_modules
     if (socket != null && behaviorList != null && behaviorList.Count > 0)
     {
         ret.AddRange(behaviorList);
         socket.Send("behavior_modules");
         var resp = socket.ReceiveString(new TimeSpan(0, 0, 0, 0, RecvTimeout));
         if (!string.IsNullOrEmpty(resp))
         {
             var modules = JArray.Parse(resp);
             if (modules != null && modules.Count > 0)
             {
                 //Console.WriteLine(resp);
                 foreach (var module in modules)
                 {
                     var moduleName = module.Value<string>("name");
                     var responder = module.SelectToken("$.responder");
                     string host = string.Empty;
                     int port = 0;
                     if (responder != null)
                     {
                         host = responder.Value<string>("Host");
                         port = responder.Value<int>("Port");
                     }
                     var behaviors = module.SelectToken("$.behaviors");
                     foreach (var behavior in behaviors)
                     {
                         string name = behavior.Value<string>("name");
                         string functionName = behavior.Value<string>("function_name");
                         var args = behavior.SelectToken("$.arg");
                         var parameters = new Dictionary<string, object>();
                         foreach (var arg in args)
                         {
                             parameters.Add(arg.Value<string>("name"), new Dictionary<string, object>
                             {
                                 {"value", arg.Value<string>("value")},
                                 {"place_holder", arg.Value<string>("place_holder")},
                                 {"type", arg.Value<string>("type")}
                             });
                         }
                         var matchingBehaviors = ret.Where(s => s.BehaviorName == name).ToList();
                         foreach (var matchingBehavior in matchingBehaviors)
                         {
                             matchingBehavior.ModuleName = moduleName;
                             matchingBehavior.FunctionName = functionName;
                             matchingBehavior.Ip = host;
                             matchingBehavior.Port = port;
                             foreach (var parameter in parameters)
                             {
                                 if (!matchingBehavior.Parameters.ContainsKey(parameter.Key))
                                 {
                                     matchingBehavior.Parameters.Add(parameter);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return ret;
 }
Esempio n. 32
0
 private static void Send(string message, NetMQSocket socket, bool sendMore = true)
 {
     socket.Send(message, false, sendMore);
 }
Esempio n. 33
0
            /// <summary>
            /// Responses the specified message.
            /// </summary>
            /// <param name="message">The message.</param>
            internal void Response(Message message)
            {
                var json = message.ToJsonString();

                socket.Send(json);
            }
Esempio n. 34
0
        public bool Publish(T msg)
        {
            _socket.Send(_msgSender(msg));

            return(true);
        }
Esempio n. 35
0
        private static void ProxyBetween(NetMQSocket from, NetMQSocket to, [CanBeNull] NetMQSocket control)
        {
            var msg = new Msg();
            msg.InitEmpty();

            var copy = new Msg();
            copy.InitEmpty();

            while (true)
            {
                from.Receive(ref msg);
                var more = msg.HasMore;

                if (control != null)
                {
                    copy.Copy(ref msg);

                    control.Send(ref copy, more);
                }

                to.Send(ref msg, more);

                if (!more)
                    break;
            }

            copy.Close();
            msg.Close();
        }
		public async Task Start ()
		{
			ThrowIfDisposed ();
			var ct = cancellationTokenSource.Token;

			nmqPoller = new Poller ();
			nmqScheduler = new NetMQScheduler (nmqContext, nmqPoller);
			nmqServer = nmqContext.CreateResponseSocket ();
			nmqServer.Bind (Address.AbsoluteUri.TrimEnd ('/'));

			serverTask = Task.Factory.StartNew (() => {
				ct.ThrowIfCancellationRequested ();

				while (true) {
					if (ct.IsCancellationRequested) {
						// clean up here
						ct.ThrowIfCancellationRequested ();
					}
					var msg = nmqServer.Receive ();
					var request = Request.Deserialize (msg);
					var result = Handle (request);

					byte[] output_buffer = result.Serialize ();
					nmqServer.Send (output_buffer);
				}
			}, ct);

			await serverTask;
		}
Esempio n. 37
0
        /// <summary>
        /// Handles incoming data "push" requests: the client sends data for us to add to local storage.
        /// </summary>
        private void AcceptDataAdditionRequest(string requesterIdentity, NetMQSocket socket)
        {
            //final message part: receive the DataAdditionRequest object
            bool hasMore;
            var ms = new MemoryStream();
            byte[] buffer = socket.Receive(out hasMore);

            var request = MyUtils.ProtoBufDeserialize<DataAdditionRequest>(buffer, ms);

            //log the request
            Log(LogLevel.Info, string.Format("Received data push request for {0}.",
                request.Instrument.Symbol));

            //start building the reply
            socket.SendMore(requesterIdentity);
            socket.SendMore("PUSHREP");
            try
            {
                _broker.AddData(request);
                socket.Send("OK");
            }
            catch (Exception ex)
            {
                socket.SendMore("ERROR");
                socket.Send(ex.Message);
            }
        }
Esempio n. 38
0
        protected override void DoServer(NetMQSocket socket, int messageSize)
        {
            var msg  = new Msg();
            msg.InitEmpty();

            for (int i = 0; i < Iterations; i++)
            {
                socket.Receive(ref msg);

                socket.Send(ref msg, more: false);
            }
        }
Esempio n. 39
0
        /// <summary>
        /// Handles requests for information on data that is available in local storage
        /// </summary>
        private void AcceptAvailableDataRequest(string requesterIdentity, NetMQSocket socket)
        {
            //get the instrument
            bool hasMore;
            var ms = new MemoryStream();
            byte[] buffer = socket.Receive(out hasMore);

            var instrument = MyUtils.ProtoBufDeserialize<Instrument>(buffer, ms);

            //log the request
            Log(LogLevel.Info, string.Format("Received local data storage info request for {0}.",
                instrument.Symbol));

            //and send the reply

            var storageInfo = _broker.GetAvailableDataInfo(instrument);
            socket.SendMore(requesterIdentity);
            socket.SendMore("AVAILABLEDATAREP");

            socket.SendMore(MyUtils.ProtoBufSerialize(instrument, ms));

            socket.SendMore(BitConverter.GetBytes(storageInfo.Count));
            foreach (StoredDataInfo sdi in storageInfo)
            {
                socket.SendMore(MyUtils.ProtoBufSerialize(sdi, ms));
            }
            socket.Send("END");
        }
Esempio n. 40
0
        private static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                SysLog.WriteError("参数不正确,请以\r\ncmd demo.exe {本机监听端口号} \r\n启动,例如\r\ndemo.exe 20000");
                Console.WriteLine("参数不正确,请以\r\ncmd demo.exe {本机监听端口号} \r\n启动,例如\r\ndemo.exe 20000");
                return;
            }
            timer.Elapsed += Timer_Tick;
            timer.Interval = 60 * 60 * 1000;
            timer.Enabled  = true;
            //new Thread(isReceivedLink).Start();
            Console.Title  = "Demo" + args[0];
            port           = args[0];
            SysLog.LogName = $"port:{args[0]}.log";
            //进程通信,给服务端通知这是开启的哪个端口
            //Info.ProInfo.GetProcessInfo(args[0]);


            while (true)
            {
                try
                {
                    //创建消息上下文对象
                    using (NetMQContext context = NetMQContext.Create())
                    {
                        //创建Socket对象

                        NetMQSocket serverSocket = context.CreateResponseSocket();

                        //绑定本地端口,监听客户端的请求,端口号与配置一致
                        serverSocket.Bind($"tcp://*:{args[0]}");
                        Console.WriteLine($"开始监听{args[0]}");
                        SysLog.WriteLog($"开始监听{args[0]}");
                        string IP = "";
                        byte[] data;
                        while (true)
                        {
                            //接收消息
                            data = serverSocket.Receive();

                            SysLog.WriteLog($"收到数据,来自:{serverSocket.Options.GetLastEndpoint}");
                            Console.WriteLine($"收到数据,来自:{serverSocket.Options.GetLastEndpoint}数据类型:{data[2]}");
                            receivedCount++;
                            //saveInFileBytes(data);
                            IP = serverSocket.Options.GetLastEndpoint;
                            if (IP.Contains(":"))
                            {
                                IP = IP.Split(':')[0];
                            }
                            try
                            {
                                //解析消息
                                IMsg msg = MsgParser.Parse(data);
                                //出现错误时,msg会为null,继续等待下次接收到的数据。
                                if (msg == null)
                                {
                                    continue;
                                }
                                //创建回复消息
                                ConfirmMsg responseMsg = new ConfirmMsg
                                {
                                    ReceiveMsgType = msg.Type,
                                    ReceiveMsgId   = "0"
                                };

                                //打印消息数据
                                switch (msg.Type)
                                {
                                //车辆消息--可以根据实际情况获取消息内容
                                case MsgType.Vehicle:
                                {
                                    VehicleMsg vMsg = msg as VehicleMsg;
                                    responseMsg.ReceiveMsgId = vMsg.Id;
                                    SysLog.WriteLog(string.Format("车辆信息:({0} {1} {2}t {3})", vMsg.Id, vMsg.EvtTime, vMsg.Weight_T, vMsg.Status));
                                    Console.WriteLine(string.Format("车辆信息:({0} {1} {2} {3}t {4} {5})", vMsg.Id, vMsg.Plate, vMsg.EvtTime, vMsg.Weight_T, vMsg.Speed, vMsg.Status));
                                    Intodb(vMsg, IP, args[0]);
                                    vMsg = null;
                                    break;
                                }

                                //称重消息--可以根据实际情况获取消息内容
                                case MsgType.Wim:
                                {
                                    WIMMsg wMsg = msg as WIMMsg;
                                    SysLog.WriteLog(string.Format("称重信息(时间:{0},车道:{1}, 轴数:{2},总重:{3}t, 车速:{4}k/h,车长: {5}m)",
                                                                  wMsg.EvtTime.ToString("yyyy-MM-dd HH:mm:ss"), wMsg.LaneNo, wMsg.AxlesCount, wMsg.Weight_T, wMsg.Speed, wMsg.Length_M));
                                    responseMsg.ReceiveMsgId = wMsg.Id;
                                    wMsg = null;
                                    break;
                                }

                                //心跳消息
                                case MsgType.Heart:
                                {
                                    SysLog.WriteLog("Heart");
                                    Console.WriteLine("Heart");
                                    break;
                                }
                                }

                                //发送回复消息
                                serverSocket.Send(responseMsg.Encode());
                            }
                            catch (Exception ex)
                            {
                                SysLog.WriteError(ex.Message);
                                Console.WriteLine(ex.Message);
                                Console.WriteLine(ex.InnerException.Message);
                                Console.WriteLine("接收数据出现错误");
                                return;
                            }

                            Console.WriteLine();
                        }
                    }
                }
                catch (SocketException es)
                {
                    SysLog.WriteError(es.Message);
                    Console.WriteLine(es.Message);
                    SysLog.WriteError("服务出错,正在软件内重启");
                    Console.WriteLine("服务出错,正在软件内重启");
                    Thread.Sleep(2000);
                }
                catch (NetMQException e2)
                {
                    SysLog.WriteError("error" + e2.InnerException.Message);
                    Console.WriteLine("error" + e2.InnerException.Message);
                    SysLog.WriteError("服务出错,正在软件内重启");
                    Console.WriteLine("服务出错,正在软件内重启");
                    Thread.Sleep(2000);
                }
                catch (Exception eall)
                {
                    SysLog.WriteError(eall.Message);
                    Console.WriteLine(eall.Message);
                    SysLog.WriteError("服务出错,正在软件内重启");
                    Console.WriteLine("服务出错,正在软件内重启");
                    Thread.Sleep(2000);
                }
            }
        }
Esempio n. 41
0
 private static void Send(string message, NetMQSocket socket, bool sendMore = true)
 {
     socket.Send(message, false, sendMore);
 }
Esempio n. 42
0
        private static void ProxyBetween(NetMQSocket from, NetMQSocket to, [CanBeNull] NetMQSocket control)
        {
            var msg = new Msg();
            msg.InitEmpty();

            var copy = new Msg();
            copy.InitEmpty();

            while (true)
            {
                from.Receive(ref msg, SendReceiveOptions.None);
                bool more = from.Options.ReceiveMore;

                if (control != null)
                {
                    copy.Copy(ref msg);

                    control.Send(ref copy, more ? SendReceiveOptions.SendMore : SendReceiveOptions.None);
                }

                to.Send(ref msg, more ? SendReceiveOptions.SendMore : SendReceiveOptions.None);

                if (!more)
                {
                    break;
                }
            }

            copy.Close();
            msg.Close();
        }
Esempio n. 43
0
        /// <summary>
        /// Query the server for contracts matching a particular set of features.
        /// </summary>
        /// <param name="instrument">An Instrument object; any features that are not null will be search parameters. If null, all instruments are returned.</param>
        /// <returns>A list of instruments matching these features.</returns>
        public List <Instrument> FindInstruments(Instrument instrument = null)
        {
            if (!Connected)
            {
                RaiseEvent(Error, this, new ErrorArgs(-1, "Could not request instruments - not connected."));
                return(new List <Instrument>());
            }

            using (NetMQSocket s = _context.CreateSocket(ZmqSocketType.Req))
            {
                s.Connect(string.Format("tcp://{0}:{1}", _host, _instrumentServerPort));
                var ms = new MemoryStream();

                if (instrument == null) //all contracts
                {
                    s.Send("ALL");
                }
                else //an actual search
                {
                    s.SendMore("SEARCH"); //first we send a search request

                    //then we need to serialize and send the instrument
                    s.Send(MyUtils.ProtoBufSerialize(instrument, ms));
                }

                //first we receive the size of the final uncompressed byte[] array
                bool   hasMore;
                byte[] sizeBuffer = s.Receive(out hasMore);
                if (sizeBuffer.Length == 0)
                {
                    RaiseEvent(Error, this, new ErrorArgs(-1, "Contract request failed, received no reply."));
                    return(new List <Instrument>());
                }

                int outputSize = BitConverter.ToInt32(sizeBuffer, 0);

                //then the actual data
                byte[] buffer = s.Receive(out hasMore);
                if (buffer.Length == 0)
                {
                    RaiseEvent(Error, this, new ErrorArgs(-1, "Contract request failed, received no data."));
                    return(new List <Instrument>());
                }

                try
                {
                    //then we process it by first decompressing
                    ms.SetLength(0);
                    byte[] decoded = LZ4Codec.Decode(buffer, 0, buffer.Length, outputSize);
                    ms.Write(decoded, 0, decoded.Length);
                    ms.Position = 0;

                    //and finally deserializing
                    return(Serializer.Deserialize <List <Instrument> >(ms));
                }
                catch (Exception ex)
                {
                    RaiseEvent(Error, this, new ErrorArgs(-1, "Error processing instrument data: " + ex.Message));
                    return(new List <Instrument>());
                }
            }
        }
Esempio n. 44
0
        public void DoWork()
        {
            using (var context = NetMQContext.Create())
            {
                using (NetMQSocket sender = context.CreatePushSocket(),
                       sink = context.CreatePushSocket())
                {
                    sink.Bind(_sinkAddress);

                    sender.Bind(_senderAddress);

                    // Wait for the workers to do their TCP thing.
                    Thread.Sleep(100);

                    Console.WriteLine("Sending tasks to workers…");

                    var randomizer = new Random(DateTime.Now.Millisecond);

                    // This is the size per 'batch'.
                    // Using this emulate reading from a file too large to fit in memory.
                    const int batchSize = 268;

                    // Set this to 200000 to simulate ~100gb of data.
                    // Current set to ~10gb of data.
                    const int numberOfBatches = 20000;

                    // 100gb = 107374182400 bytes.
                    // 100gb / 20 = 53687091 words in file
                    // 53687091 / 200000 = ~268 words per 'batch'.
                    // That's around 50kb per chunk. Seems reasonable.
                    // Using TCP right now, could use inproc too.

                    int currentBatch = 0;
                    while (currentBatch < numberOfBatches)
                    {
                        // Just putting it all in a big string that's sent over ZeroMQ.
                        // Separated by commas, but it's arbitrary.
                        StringBuilder workToSend = new StringBuilder();

                        workToSend.Append(string.Format("#{0},", currentBatch));

                        // Random 'word' to send workers
                        for (int i = 0; i < batchSize; i++)
                        {
                            // We can tweak the number of unique keys here...
                            // More unique keys is more expensive to write to disk.
                            // Anything greater than 3020000 results in huuuuge flushes to
                            // The disk and gets pretty slow.
                            // Anything less than that can remain in memory (with 4gb).
                            // Best solution: Virtual Memory. You can keep pointers in memory
                            // And not have manually handle flushing to the disk yourself.
                            workToSend.Append(randomizer.Next(1, 5000000) + ",");
                        }

                        // Print out some output to show we're working.
                        if (currentBatch % 10000 == 0)
                        {
                            Console.WriteLine("{0}% Complete pushing work", ((double)currentBatch / (double)numberOfBatches * 100).ToString("0.0"));
                        }

                        sink.Send("#" + currentBatch);
                        sender.Send(workToSend.ToString().TrimEnd(','));

                        currentBatch++;
                    }

                    Console.WriteLine("Done with queueing every job! Sending done to Sink.");

                    sink.Send("done");

                    IsWorking = false;
                }
            }
        }