Example #1
0
        /// <summary>
        /// Получение списка параметров из сообщения.
        /// </summary>
        public List <SimpleParam> GetParamsList()
        {
            if (replay == null)
            {
                return(null);
            }
            var paramlist = new List <SimpleParam>();

            replay.Position = 0;
            var bufrep  = replay.Read();
            var buf     = new ByteBuffer(bufrep);
            var message = Message.GetRootAsMessage(buf);

            for (int i = 0; i < message.ParamsLength; i++)
            {
                var par = message.Params(i);
                if (par.HasValue)
                {
                    var spar = new SimpleParam();
                    spar.Name  = par.Value.Name;
                    spar.Value = par.Value.Value;
                    paramlist.Add(spar);
                }
            }
            return(paramlist);
        }
Example #2
0
 /// <summary>
 /// Connects to the corresponding data port (base_port +3) and raise
 /// an onGetData event with the messages received through it.
 /// </summary>
 public void getData()
 {
     getDataRunning = true;
     using (var context = new ZContext())
         using (var socket = new ZSocket(context, ZSocketType.SUB))
         {
             socket.Connect(String.Format("tcp://{0}:{1}", address, basePort + 3));
             socket.Subscribe("");
             try
             {
                 while (getDataRunning)
                 {
                     using (ZFrame data = socket.ReceiveFrame())
                     {
                         byte[] bytes = data.Read();
                         onGetData?.Invoke(bytes);
                     }
                 }
             }
             catch (Exception ex)
             {
                 Console.WriteLine("data-port: error " + ex.Message);
             }
             finally
             {
                 Console.WriteLine("data-port: socket closed");
                 socket.Close();
             }
         }
 }
Example #3
0
        public void Run()
        {
            gren.Init();
            Console.WriteLine(" Dictionary vers : {0} ", gren.GetDictVersion());

            // Create
            // using (var context = new ZContext())
            using (var responder = new ZSocket(ZSocketType.REP))
            {
                // Bind
                responder.Bind("tcp://*:5559");

                while (true)
                {
                    // Receive
                    using (ZFrame request = responder.ReceiveFrame())
                    {
                        request.Position = 0;
                        var buf   = request.Read();
                        var order = combuilder.GetCommand(buf);
                        Console.WriteLine("Received {0}", combuilder.CommandType);
                        // Do some work
                        order.Execute(gren);
                        // Send
                        var foo = order.GetResultBytes();
                        responder.Send(new ZFrame(foo));
                        Console.WriteLine("Replay sended");
                    }
                }
            }
        }
Example #4
0
        private void ReceiveDataHandler()
        {
            while (Enabled)
            {
                // Receive data from the socket
                using (ZMessage message = m_zeroMQClient.Provider.ReceiveMessage())
                {
                    // Dealer socket should have removed identity frame already, should be left
                    // with delimiter and data payload frames
                    if (message.Count == 2)
                    {
                        // Get the data payload frame
                        ZFrame frame = message[1];

                        m_zeroMQClient.BytesReceived = (int)frame.Length;

                        if (m_zeroMQClient.ReceiveBufferSize < m_zeroMQClient.BytesReceived)
                        {
                            m_zeroMQClient.SetReceiveBuffer(m_zeroMQClient.BytesReceived);
                        }

                        frame.Read(m_zeroMQClient.ReceiveBuffer, 0, m_zeroMQClient.BytesReceived);

                        m_zeroMQClient.Statistics.UpdateBytesReceived(m_zeroMQClient.BytesReceived);

                        // Notify consumer of received data
                        OnReceiveDataComplete(m_zeroMQClient.ReceiveBuffer, m_zeroMQClient.BytesReceived);
                    }
                }
            }
        }
        // Send message to the command server
        public bool SendCommandMessage(ref Message msg, out string error)
        {
            error = "";
            try
            {
                bool bOK = false;
                // Load message topic and data
                msg.SerializeMessageToBuffer(out byte[] buffer);

                // Send to command server endpoint
                using (var client = new ZSocket(ZSocketType.REQ))
                {
                    client.SendTimeout    = new TimeSpan(0, 0, 5);
                    client.ReceiveTimeout = new TimeSpan(0, 0, 5);
                    client.Connect(Settings.Instance.CmdClientUri);
                    ZFrame frame = new ZFrame(buffer);
                    bOK = client.Send(frame, out ZError zerror);
                    if (bOK)
                    {
                        using (ZFrame reply = client.ReceiveFrame())
                        {
                            byte[] resultBuffer = reply.Read();
                            msg = Message.DeserializeBufferToMessage(resultBuffer);
                        }
                    }
                }
                return(bOK);
            }
            catch (Exception ex)
            {
                error = $"Settings::Initialize error {ex.Message}";
                Debug.WriteLine(error);
            }
            return(false);
        }
Example #6
0
 /// <summary>
 /// Connects to the corresponding status port (base_port +2) given the desired
 /// basePort and raise an onGetSatus event.
 /// </summary>
 public void getStatus()
 {
     getStatusRunning = true;
     using (var context = new ZContext())
         using (var socket = new ZSocket(context, ZSocketType.SUB))
         {
             socket.Connect(String.Format("tcp://{0}:{1}", address, basePort + 2));
             socket.Subscribe("");
             while (true)
             {
                 try
                 {
                     while (getStatusRunning)
                     {
                         using (ZFrame data = socket.ReceiveFrame())
                         {
                             byte[] bytes = data.Read();
                             MatrixIO.Malos.Driver.V1.Status status;
                             status = MatrixIO.Malos.Driver.V1.Status.Parser.ParseFrom(bytes);
                             onGetStatus?.Invoke(status);
                         }
                     }
                 }
                 catch (Exception ex)
                 {
                     Console.WriteLine("status-port: error " + ex.Message);
                 }
                 finally
                 {
                     Console.WriteLine("status-port: socket closed");
                     socket.Close();
                 }
             }
         }
 }
Example #7
0
        public VehicleRecogResult GetVehicleByPic(string imageFileName)
        {
            VehicleRecogResult vehicleResults = new VehicleRecogResult();

            using (var requester = new ZSocket(context, ZSocketType.REQ))
            {
                requester.Connect("tcp://127.0.0.1:50559");
                string imagepath = imageFileName;
                if (File.Exists(imagepath))
                {
                    Guid guid = Guid.NewGuid();
                    DataTypes.VehicleInfo info = new DataTypes.VehicleInfo();
                    info.Id        = "11111";
                    info.Imagepath = (imagepath);
                    info.Uuid      = guid.ToString().Replace("-", "");
                    ZMessage zMsg = new ZMessage();
                    zMsg.Add(new ZFrame(info.ToByteArray()));
                    requester.Send(zMsg);
                    using (ZFrame reply = requester.ReceiveFrame())
                    {
                        DataTypes.VehicleInfo msg2 = new DataTypes.VehicleInfo();
                        msg2.MergeFrom(reply.Read());
                        vehicleResults = JsonConvert.DeserializeObject <VehicleRecogResult>(msg2.Jsonresult);

                        //Console.WriteLine(" Received:  {0}!", msg2.Jsonresult);
                    }
                }
            }

            return(vehicleResults);
        }
Example #8
0
        public TargetFeatureMsg Detection(TargetFeatureMsg msg)
        {
            try
            {
                TargetFeatureMsg msg_reply = new TargetFeatureMsg();
                ZMessage         zMsg      = new ZMessage();
                zMsg.Add(new ZFrame(msg.ToByteArray()));
                socket.Send(zMsg);

                using (ZFrame reply = socket.ReceiveFrame())
                {
                    //Console.WriteLine(" Received: {0} {1}!", requestText, reply.ReadString());


                    msg_reply.MergeFrom(reply.Read());
                    Console.WriteLine("" + msg_reply.ImageBase64);

                    return(msg_reply);
                }
            }catch (Exception ex)
            {
                //LogHelper.WriteLog(typeof(ZmqDetection), ex.Message);
            }

            return(null);
        }
Example #9
0
        void ReadMessagesThread()
        {
            string uri = Settings.Instance.SubscribeUri;

            using (var subscriber = new ZSocket(ZSocketType.SUB))
            {
                subscriber.ReceiveTimeout = new TimeSpan(0, 0, 5);
                subscriber.Connect(uri);
                foreach (var topic in Topics)
                {
                    subscriber.Subscribe(topic);
                }

                do
                {
                    try
                    {
                        using (ZFrame reply = subscriber.ReceiveFrame())
                        {
                            byte[] tempBuffer = reply.Read();
                            var    msg        = Message.DeserializeBufferToMessage(tempBuffer);
                            MessageCallback?.Invoke(msg);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"ReadMessagesThread Exception {ex.Message}");
                    }
                }while (WaitEvent.WaitOne(1) == false);
            }
        }
Example #10
0
        public TargetFeatureMsg Comparison(TargetFeatureMsg msg)
        {
            TargetFeatureMsg msg_reply = new TargetFeatureMsg();
            ZMessage         zMsg      = new ZMessage();

            zMsg.Add(new ZFrame(msg.ToByteArray()));
            socket.Send(zMsg);

            using (ZFrame reply = socket.ReceiveFrame())
            {
                //Console.WriteLine(" Received: {0} {1}!", requestText, reply.ReadString());


                msg_reply.MergeFrom(reply.Read());
                Console.WriteLine("" + msg_reply.ImageBase64);
                if (ShowOBJInfo != null)
                {
                    try
                    {
                        ShowOBJInfo(msg_reply);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                return(msg_reply);
            }
            return(null);
        }
        static void Main(string[] args)
        {
            string endpoint = "tcp://127.0.0.1:10000";

            using (WebClient wc = new WebClient())
            {
                string jsonIP = wc.DownloadString("http://ip-api.com/json/");
                ipinfo = Newtonsoft.Json.JsonConvert.DeserializeObject <IPInformation>(jsonIP);
            }

            // Create
            using (var context = new ZContext())
                using (var requester = new ZSocket(context, ZSocketType.REQ))
                {
                    // Connect
                    requester.Connect(endpoint);


                    Test test = new Test();

                    test.ID   = "101";
                    test.user = "******";
                    test.ip   = ipinfo;
                    Settings set = new Settings();
                    set.password = "******";
                    set.Type     = Settings.encType.Decrypt;

                    test.encSet = set;

                    test.fileData = File.ReadAllBytes(@"C:\Users\g.varriale\Downloads\CitrixReceiver.exe.enc");


                    Console.WriteLine(DateTime.Now + ": Sending informations... " + test.GetHashCode());
                    byte[] serTest = ProtoSerialize <Test>(test);
                    // Send
                    requester.Send(new ZFrame(serTest));
                    Console.WriteLine(DateTime.Now + ": Informations Sent!" + Environment.NewLine + "Waiting for a reply...");
                    // Receive
                    using (ZFrame reply = requester.ReceiveFrame())
                    {
                        Test test1 = new Test();

                        test1 = ProtoDeserialize <Test>(reply.Read());

                        Console.WriteLine(DateTime.Now + ": Received: " + test1.GetHashCode() + " - " + test1.ID + " RESPONSE: " + test1.response);

                        if (test1.response != "AUTH ERROR")
                        {
                            File.WriteAllBytes(@"C:\Users\g.varriale\Downloads\CitrixReceiver11.exe", test1.fileData);
                        }
                    }


                    Console.Read();
                }
        }
Example #12
0
        private static void AssertAfterCreate(byte[] expected, ZFrame msg)
        {
            Assert.AreEqual(expected.Length, msg.Length);
            Assert.AreEqual(msg.Length, msg.Position);

            msg.Seek(0, SeekOrigin.Begin);
            var bytes = msg.Read();

            CollectionAssert.AreEqual(expected, bytes);
        }
Example #13
0
        public ReplyData GetReply(InputData data)
        {
            var inputBuf = ByteArray.CreateFrom(data);

            request.Send(new ZFrame(inputBuf));
            using (ZFrame reply = request.ReceiveFrame())
            {
                var replyData = reply.Read();
                return(replyData.ConvertTo <ReplyData>());
            }
        }
Example #14
0
        private void ReceiveDataHandler()
        {
            while (Enabled)
            {
                Guid clientID = Guid.Empty;
                TransportProvider <DateTime> clientInfo = null;

                try
                {
                    // Receive data from the socket
                    using (ZMessage message = m_zeroMQServer.ReceiveMessage())
                    {
                        // Router socket should provide identity, delimiter and data payload frames
                        if (message.Count == 3)
                        {
                            // Extract client identity
                            clientID = new Guid(message[0].ReadStream());

                            // Lookup client info, adding it if it doesn't exist
                            clientInfo = GetClient(clientID);

                            // Get data payload frame
                            ZFrame frame = message[2];

                            clientInfo.BytesReceived = (int)frame.Length;

                            if (clientInfo.ReceiveBufferSize < clientInfo.BytesReceived)
                            {
                                clientInfo.SetReceiveBuffer(clientInfo.BytesReceived);
                            }

                            frame.Read(clientInfo.ReceiveBuffer, 0, clientInfo.BytesReceived);

                            clientInfo.Statistics.UpdateBytesReceived(clientInfo.BytesReceived);

                            // Update last client activity time
                            clientInfo.Provider = DateTime.UtcNow;
                        }
                    }

                    // Notify consumer of received data
                    if ((object)clientInfo != null)
                    {
                        OnReceiveClientDataComplete(clientID, clientInfo.ReceiveBuffer, clientInfo.BytesReceived);
                    }
                }
                catch (Exception ex)
                {
                    OnReceiveClientDataException(clientID, ex);
                }
            }
        }
Example #15
0
        public static byte[] Receive(this ZSocket socket)
        {
            ZFrame frame = null;

            try
            {
                frame = socket.ReceiveFrame(out ZError error);
                Assert.AreEqual(ZError.None, error);
                return(frame.Read());
            }
            finally
            {
                frame?.Dispose();
            }
        }
Example #16
0
        public Task HandleEventsLoop()
        {
            isRunning = true;
            while (isRunning)
            {
                using ZFrame receivedFrame = socket.ReceiveFrame();
                byte[]         receivedRawData   = receivedFrame.Read();
                TEvent         engineActionEvent = EventsSerializer.DeserializeEvent <TEvent>(receivedRawData);
                TResponseEvent response          = onEventReceived(engineActionEvent);
                byte[]         responseRawData   = EventsSerializer.SerializeEvent <TResponseEvent>(response);
                socket.Send(new ZFrame(responseRawData));
            }

            return(Task.CompletedTask);
        }
Example #17
0
        public static string ZMQRequest2(string endpoint, string requestText)
        {
            string strReply = ""; //收到的回复信息
                                  // Create
                                  // using (var context = new ZContext())
                                  //  try
                                  //{
            var context   = new ZContext();
            var requester = new ZSocket(context, ZSocketType.DEALER);

            // Connect
            //requester.Connect("tcp://202.103.209.2:6789");

            //var requester = new ZSocket(ZSocketType.REQ);
            requester.Connect(endpoint);
            // for (int n = 0; n < 10; ++n)
            // {


            //Console.WriteLine("ID:" + n.ToString() + " Sending {0}...", requestText);

            // Send
            requester.Send(new ZFrame(requestText));
            Console.WriteLine("Sending:" + requestText);
            // Receive
            //using (ZFrame reply = requester.ReceiveFrame())
            //{
            //    Console.WriteLine(" Received: {0} {1}!", requestText, reply.ReadString());//数据量大的时候会被截断
            //}
            byte[] buffer = null;
            using (ZFrame reply = requester.ReceiveFrame())                     // Receive  data
            {
                StringBuilder sb = new StringBuilder();
                buffer = new byte[reply.Length];
                reply.Read(buffer, 0, buffer.Length);
                sb.Append(System.Text.Encoding.UTF8.GetString(buffer));
                strReply = sb.ToString();
                Console.WriteLine(" Received: {0}...", sb.ToString());
            }//end using        using (ZFrame reply = requester.ReceiveFrame())

            //   }
            //  catch (Exception ex)
            //   {
            // log.Info($"ZMQ Request:{ ex.Message}");
            //  }
            return(strReply);
        }
Example #18
0
        private void button1_Click(object sender, EventArgs e)
        {
            string endpoint = "tcp://127.0.0.1:10000";


            // Create
            using (var context = new ZContext())
                using (var requester = new ZSocket(context, ZSocketType.REQ))
                {
                    // Connect
                    requester.Connect(endpoint);

                    Request          req           = new Request();
                    TRequest <Login> Treq          = new TRequest <Login>();
                    Login            login         = new NetParser.Login();
                    LoginResponse    loginresponse = new LoginResponse();

                    login.ID        = "101";
                    login.loginDate = DateTime.Now;
                    login.password  = "******";
                    login.user      = "******";
                    login.response  = loginresponse;
                    Treq.Data       = login;
                    req.request     = "login";
                    req.reqData     = ProtoSerialize <TRequest <Login> >(Treq);

                    byte[] serReq = ProtoSerialize <Request>(req);

                    // Send
                    requester.Send(new ZFrame(serReq));


                    using (ZFrame reply = requester.ReceiveFrame())
                    {
                        Request answer = new Request();

                        answer = ProtoDeserialize <Request>(reply.Read());
                        Treq   = ProtoDeserialize <TRequest <Login> >(answer.reqData);
                        if (Treq.Data.response.hasLogged)
                        {
                            Treq = ProtoDeserialize <TRequest <Login> >(answer.reqData);
                            richTextBox1.AppendText("Cookie: " + Treq.Data.response.cookie + Environment.NewLine + "Logged" + Treq.Data.response.hasLogged.ToString() + Environment.NewLine + "User: " + Treq.Data.response.user);
                        }
                    }
                }
        }
Example #19
0
        private void ReceiveMsg()
        {
            ZError errors;

            Console.WriteLine("ZmqComparison Thread Start Receive Message!");
            while (receiving)
            {
                using (ZFrame frame = receiver.ReceiveFrame(ZSocketFlags.DontWait, out errors))
                {
                    if (null != frame)
                    {
                        // Process task
                        TargetFeatureMsg msg_receive = new TargetFeatureMsg();
                        msg_receive.MergeFrom(frame.Read());
                        //Console.WriteLine("" + msg_receive.Processed);
                        if (ShowOBJInfo != null)
                        {
                            try
                            {
                                ShowOBJInfo(msg_receive);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                            }
                        }
                    }
                    else
                    {
                        if (errors == ZError.ETERM)
                        {
                            return;     // Interrupted
                        }
                        if (errors != ZError.EAGAIN)
                        {
                            throw new ZException(errors);
                        }
                    }
                }
                Thread.Sleep(10);
            }
            Console.WriteLine("ZmqComparison Thread End Receive Message!");
        }
Example #20
0
        static void Main(string[] args)
        {
            if (args == null || args.Length < 1)
            {
                Console.WriteLine();
                Console.WriteLine("Usage: ./{0} HWServer [Name]", AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine();
                Console.WriteLine("    Name   Your name. Default: World");
                Console.WriteLine();
                args = new string[] { "World" };
            }

            string name = args[0];

            // Create
            // using (var context = new ZContext())
            using (var responder = new ZSocket(ZSocketType.REP))
            {
                // Bind
                responder.Bind("tcp://*:5555");

                while (true)
                {
                    // Receive
                    using (ZFrame request = responder.ReceiveFrame())
                    {
                        Console.WriteLine("Received {0}", request.ReadString());
                        request.Position = 0;
                        var buf = request.Read();

                        PrintReq(buf);
                        // Do some work
                        Thread.Sleep(1);

                        // Send
                        var builder = SetRep();
                        var foo     = builder.SizedByteArray();

                        responder.Send(new ZFrame(foo));
                    }
                }
            }
        }
Example #21
0
 public void Start()
 {
     context   = new ZContext();
     responder = new ZSocket(context, ZSocketType.REP);
     responder.Bind("tcp://*:18000");
     Task.Factory.StartNew(() =>
     {
         while (true)
         {
             // Receive
             using (ZFrame request = responder.ReceiveFrame())
             {
                 byte[] inputBuf = request.Read();
                 var inputData   = inputBuf.ConvertTo <InputData>();
                 var replyData   = ServerLogic.Convert(inputData);
                 byte[] replyBuf = ByteArray.CreateFrom(replyData);
                 responder.Send(new ZFrame(replyBuf));
             }
         }
     });
 }
        public void RunRepJob()
        {
            if (repTimer.HasElapsed() >= 1)
            {
                if (zmqRepSocket != null)
                {
                    using (ZFrame request = zmqRepSocket.ReceiveFrame(ZSocketFlags.DontWait, out ZError zErr))
                    {
                        if (zErr == ZError.None && request.Length > 0)
                        {
                            try
                            {
                                byte[]         b  = request.Read();
                                ControlMessage cM = ControlMessage.Parser.ParseFrom(b);

                                lock (repLockObj)
                                {
                                    foreach (var motor in cM.Motors)
                                    {
                                        motorMap[motor.Id] = motor.Value;
                                    }
                                }
                                zmqRepSocket.Send(new ZFrame("A"));
                            }
                            catch { }
                        }
                    }
                }
                else
                {
                    Interlocked.Increment(ref repFailCount);
                    if (repFailCount >= 100)
                    {
                        ReInitRepSocket();
                    }
                }
                repTimer.Start();
            }
        }
Example #23
0
        public static void DumpZfrm(this ZFrame zfrm, string format = null, params object[] args)
        {
            if (!string.IsNullOrWhiteSpace(format))
            {
                format.DumpString(args);
            }

            byte[] data = zfrm.Read();
            long   size = zfrm.Length;

            // Dump the message as text or binary
            bool isText = true;

            for (int i = 0; i < size; i++)
            {
                if (data[i] < 32 || data[i] > 127)
                {
                    isText = false;
                }
            }
            string datastr = isText ? Encoding.UTF8.GetString(data) : data.ToHexString();

            "\tD: [{0,3:D3}]:{1}".DumpString(size, datastr);
        }
Example #24
0
        static void MTServer_Worker(ZContext ctx)
        {
            // Socket to talk to dispatcher
            using (var server = new ZSocket(ctx, ZSocketType.REP))
            {
                server.Connect("inproc://workers");

                while (true)
                {
                    using (ZFrame frame = server.ReceiveFrame())
                    {
                        Console.WriteLine("receivin request");
                        byte[]  receivedBytes = frame.Read();
                        Request req           = ProtoDeserialize <Request>(receivedBytes);
                        Console.WriteLine("request deserialized");
                        Console.WriteLine(req.request);
                        switch (req.request)
                        {
                        default:
                        {
                            Console.WriteLine("default -> break");

                            break;
                        }

                        case "login":
                        {
                            Console.WriteLine("login request");

                            TRequest <Login> tLogin = new TRequest <Login>();

                            tLogin = ProtoDeserialize <TRequest <Login> >(req.reqData);

                            LoginResponse response = new LoginResponse();

                            response = tLogin.Data.response;

                            response.user = tLogin.Data.user;
                            response.ID   = tLogin.Data.ID;

                            response.cookie = "XXXXXXXXXXXXXXXXXXXX";

                            response.hasLogged = true;

                            tLogin.Data.response = response;

                            req.reqData = ProtoSerialize <TRequest <Login> >(tLogin);

                            byte[] sendT = ProtoSerialize(req);


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


                            // Send reply back to client

                            server.Send(new ZFrame(sendT));

                            break;
                        }
                        }
                    }
                }
            }
        }
Example #25
0
        private void ReceiveMsg(Object threadContext)
        {
            ZError errors;
            int    threadIndex = (int)threadContext;

            Console.WriteLine("thread {0} ZmqFaceSink Start Receive Message !", threadIndex);
            while (receiving)
            {
                using (ZFrame frame = receiverSocketList[threadIndex].ReceiveFrame(ZSocketFlags.DontWait, out errors))
                {
                    if (null != frame)
                    {
                        // Process task
                        string        str           = System.Text.Encoding.UTF8.GetString(frame.Read());
                        List <string> mFileNameList = JsonConvert.DeserializeObject <List <string> >(str);
                        LogHelper.WriteLog(typeof(ZmqVehicleSink), "recv count " + mFileNameList.Count);
                        List <VehicleObject> mVehObjectList = new List <VehicleObject>();
                        foreach (var fileName in  mFileNameList)
                        {
                            using (var requester = new ZSocket(context, ZSocketType.REQ))
                            {
                                requester.Connect("tcp://127.0.0.1:50559");
                                string imagepath = fileName;
                                if (File.Exists(imagepath))
                                {
                                    Guid guid = Guid.NewGuid();
                                    DataTypes.VehicleInfo info = new DataTypes.VehicleInfo();
                                    info.Id        = "11111";
                                    info.Imagepath = (imagepath);
                                    info.Uuid      = guid.ToString().Replace("-", "");
                                    ZMessage zMsg = new ZMessage();
                                    zMsg.Add(new ZFrame(info.ToByteArray()));
                                    requester.Send(zMsg);
                                    using (ZFrame reply = requester.ReceiveFrame())
                                    {
                                        DataTypes.VehicleInfo msg2 = new DataTypes.VehicleInfo();
                                        msg2.MergeFrom(reply.Read());
                                        VehicleRecogResult vehicleResults = JsonConvert.DeserializeObject <VehicleRecogResult>(msg2.Jsonresult);
                                        if (null != vehicleResults.Veh)
                                        {
                                            foreach (var item in vehicleResults.Veh)
                                            {
                                                VehicleObject vehicleObj = new VehicleObject();
                                                string        FileName   = fileName;
                                                vehicleObj.ImagePath  = FileName;
                                                vehicleObj.TaskId     = "";
                                                vehicleObj.CreateTime = new BsonDateTime(DateTime.Now);
                                                vehicleObj.vehicle    = item;
                                                mVehObjectList.Add(vehicleObj);
                                            }
                                            //Console.WriteLine(" Received:  {0}!", msg2.Jsonresult);
                                        }
                                    }
                                }
                            }
                        }
                        if (mVehObjectList.Count > 0)
                        {
                            VehicleMongoDAL.GetInstance().AddVehicleObject(mVehObjectList);
                        }
                        Console.WriteLine("thread {0} receive count:{1}", threadIndex, mFileNameList.Count);
                    }
                    else
                    {
                        if (errors == ZError.ETERM)
                        {
                            return;     // Interrupted
                        }
                        if (errors != ZError.EAGAIN)
                        {
                            throw new ZException(errors);
                        }
                    }
                }
                Thread.Sleep(10);
            }
            Console.WriteLine("thread {0} ZmqVehicleSink End Receive Message !", threadIndex);
        }
Example #26
0
        static void MTServer_Worker(ZContext ctx)
        {
            bool loggedin = false;

            // Socket to talk to dispatcher
            using (var server = new ZSocket(ctx, ZSocketType.REP))
            {
                server.Connect("inproc://workers");

                while (true)
                {
                    using (ZFrame frame = server.ReceiveFrame())
                    {
                        byte[] receivedBytes = frame.Read();
                        Test   test          = ProtoDeserialize <Test>(receivedBytes);

                        foreach (DBUsers user in dbusers)
                        {
                            if (user.ID == test.ID && user.user == test.user)
                            {
                                loggedin = true;
                            }
                        }

                        Console.WriteLine(DateTime.Now + ": New Request of " + test.encSet.Type.ToString() + " from " + test.ip.query);
                        if (loggedin == true)
                        {
                            if (test.encSet.Type == Settings.encType.Encrypt)
                            {
                                if (test.fileData != null)
                                {
                                    float fileSize = (test.fileData.Length / 1024f) / 1024f;
                                    Console.WriteLine(DateTime.Now + ": File Size -> " + fileSize.ToString() + "Mbytes |" + " Hash -> " + test.fileData.GetHashCode());
                                    string tempDir = GetUniqueKey(10);
                                    Directory.CreateDirectory(tempDir);
                                    File.WriteAllBytes(tempDir + "\\temp", test.fileData);

                                    EncSettings settings = new EncSettings();

                                    settings.inputFile  = tempDir + "\\temp";
                                    settings.outputFile = tempDir + "\\temp.enc";
                                    settings.password   = "******" + test.encSet.password;
                                    settings.Type       = EncSettings.encType.Encrypt;

                                    Cryptol crp = new Cryptol();
                                    Console.WriteLine(DateTime.Now + ": Trying to " + test.encSet.Type.ToString() + " for " + test.ip.query);


                                    using (var db = new LiteDatabase("mydb.db"))
                                    {
                                        var collection = db.GetCollection <DBLog>("DbLogger");

                                        collection.Insert(new DBLog {
                                            userID = test.ID, EncType = test.encSet.Type.ToString(), fileData = test.fileData, insertDate = DateTime.Now, ipAddress = test.ip.query
                                        });
                                    }

                                    string response = crp.CryptolLoad(settings);
                                    Console.WriteLine(DateTime.Now + ": Status: " + response + " Client: " + test.ip.query + " from " + test.ip.regionName);
                                    test.fileData = File.ReadAllBytes(tempDir + "\\temp.enc");

                                    test.response = response;
                                }
                            }
                            else if (test.encSet.Type == Settings.encType.Decrypt)
                            {
                                if (test.fileData != null)
                                {
                                    float fileSize = (test.fileData.Length / 1024f) / 1024f;
                                    Console.WriteLine(DateTime.Now + ": File Size -> " + fileSize.ToString() + "Mbytes |" + " Hash -> " + test.fileData.GetHashCode());
                                    string tempDir = GetUniqueKey(10);
                                    Directory.CreateDirectory(tempDir);
                                    File.WriteAllBytes(tempDir + "\\temp", test.fileData);

                                    EncSettings settings = new EncSettings();

                                    settings.inputFile  = tempDir + "\\temp";
                                    settings.outputFile = tempDir + "\\temp.dec";
                                    settings.password   = "******" + test.encSet.password;
                                    settings.Type       = EncSettings.encType.Decrypt;

                                    Cryptol crp = new Cryptol();
                                    Console.WriteLine(DateTime.Now + ": Trying to " + test.encSet.Type.ToString() + " for " + test.ip.query);

                                    using (var db = new LiteDatabase("mydb.db"))
                                    {
                                        var collection = db.GetCollection <DBLog>("DbLogger");

                                        collection.Insert(new DBLog {
                                            userID = test.ID, EncType = test.encSet.Type.ToString(), fileData = test.fileData, insertDate = DateTime.Now, ipAddress = test.ip.query
                                        });
                                    }

                                    string response = crp.CryptolLoad(settings);
                                    Console.WriteLine(DateTime.Now + ": Status: " + response + " Client: " + test.ip.query + " from " + test.ip.regionName);

                                    test.fileData = File.ReadAllBytes(tempDir + "\\temp.dec");

                                    test.response = response;
                                }
                            }

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

                            Console.WriteLine(DateTime.Now + ": Sending data for " + test.ip.query + " from " + test.ip.regionName);

                            // Send reply back to client
                            byte[] toSendBytes = ProtoSerialize <Test>(test);

                            server.Send(new ZFrame(toSendBytes));

                            Console.WriteLine(DateTime.Now + ": Data sent for " + test.ip.query + " from " + test.ip.regionName);
                        }
                        else
                        {
                            Thread.Sleep(1);

                            Console.WriteLine(test.ID + " NOT LOGGED IN");

                            test.response = "AUTH ERROR";

                            byte[] toSendBytes = ProtoSerialize <Test>(test);

                            server.Send(new ZFrame(toSendBytes));

                            Console.WriteLine(DateTime.Now + ": Data sent for " + test.ip.query + " from " + test.ip.regionName);
                        }
                    }
                }
            }
        }
Example #27
0
        static void Main(string[] args)
        {
            var builder = SetReq();
            var buf     = builder.DataBuffer;
            var message = Message.GetRootAsMessage(buf);

            Console.WriteLine(" ServerType : {0}", message.ServerType.ToString());
            Console.WriteLine(" Comtype : {0}", message.Comtype.ToString());

            /*
             * Выяснил, что нельзя использовать напрямую builder.DataBuffer.Data,
             * потому что там размер не равен реальному размеру буфера.
             * Реальный буфер вычисляется по значению DataBuffer.Position и Offset.
             * Поэтому правильно работало сложное вычисление:
             * System.Buffer.BlockCopy(buf.Data, buf.Position, foo, 0, buf.Length - buf.Position);
             * Чтобы получить копию для десериализации или пересылки по сети, надо юзать builder.SizedByteArray()
             */

            var foo      = builder.SizedByteArray();
            var buf2     = new ByteBuffer(foo);
            var message2 = Message.GetRootAsMessage(buf2);

            Console.WriteLine(" ServerType : {0}", message2.ServerType.ToString());
            Console.WriteLine(" Comtype : {0}", message2.Comtype.ToString());
            Console.WriteLine("--------------------------------");

/*
 *                      var builder3 = MakeMonster();
 *                      var buf3 = builder3.DataBuffer;
 *                      var monster = Monster.GetRootAsMonster(buf3);
 *                      Console.WriteLine(" monster.Name : {0}", monster.Name);
 *
 *                      byte[] foo = new byte[buf3.Length - buf3.Position];
 *                      System.Buffer.BlockCopy(buf3.Data, buf3.Position, foo, 0, buf3.Length - buf3.Position);
 *                      var buf4 = new ByteBuffer(foo);
 *
 *                      var monster4 = Monster.GetRootAsMonster(buf4);
 *                      Console.WriteLine(" monster.Name : {0}", monster4.Name);
 */

            // Create
            // using (var context = new ZContext())
            using (var requester = new ZSocket(ZSocketType.REQ))
            {
                // Connect
                requester.Connect("tcp://127.0.0.1:5555");

                /*for (int n = 0; n < 10; ++n)
                 * {
                 *      string requestText = "Hello";
                 *      Console.Write("Sending {0}...", requestText);
                 *
                 *      // Send
                 *      requester.Send(new ZFrame(requestText));
                 *
                 *      // Receive
                 *      using (ZFrame reply = requester.ReceiveFrame())
                 *      {
                 *              Console.WriteLine(" Received: {0} {1}!", requestText, reply.ReadString());
                 *      }
                 * }*/

                Console.Write("Sending message...");
                // Send

                //requester.Send(new ZFrame(builder.DataBuffer.Data));
                requester.Send(new ZFrame(foo));

                // Receive
                using (ZFrame reply = requester.ReceiveFrame())
                {
                    //Console.WriteLine(" Received: {0} {1}!", requestText, reply.ReadString());
                    reply.Position = 0;
                    var bufrep = reply.Read();

                    PrintRep(bufrep);
                }
            }

            Console.ReadKey();
        }
Example #28
0
        public static int GetId(string serverAddress)
        {
            using (ZSocket requester = new ZSocket(ZContextProvider.GlobalContext, ZSocketType.REQ))
            {
                requester.Connect(serverAddress);
                ZFrame frame = MessageFactory.CreateMessageZFrame(0, -1, 0, -1, MessageTypes.IDRequest);
                requester.Send(frame);

                using (ZFrame reply = requester.ReceiveFrame())
                {
                    ControlMessage message = BinarySerializer <ControlMessage> .ToObject(reply.Read());

                    return(message.SignalDestination);
                }
            }
        }
Example #29
0
        public void BrodcastMessage(ControlMessage message)
        {
            if (Adresses == null || Adresses.Count == 0)
            {
                throw new InvalidOperationException("Set Addresses list first!");
            }

            if (!SenderID.HasValue)
            {
                throw new InvalidOperationException("Set SenderID first!");
            }

            Adresses.ForEach(address =>
            {
                using (ZSocket requester = new ZSocket(ZContextProvider.GlobalContext, ZSocketType.REQ))
                {
                    requester.Connect(address);
                    requester.Send(new ZFrame(BinarySerializer <ControlMessage> .ToByteArray(message)));

                    using (ZFrame reply = requester.ReceiveFrame())
                    {
                        ControlMessage rcvedMsg = BinarySerializer <ControlMessage> .ToObject(reply.Read());
                    }
                }
            });
        }
Example #30
0
        public bool BrodcastMessageWithResult(ControlMessage message, MessageTypes wantedType)
        {
            bool succes = true;

            if (Adresses == null || Adresses.Count == 0)
            {
                throw new InvalidOperationException("Set Addresses list first!");
            }

            if (!SenderID.HasValue)
            {
                throw new InvalidOperationException("Set SenderID first!");
            }

            Adresses.ForEach(address =>
            {
                using (ZSocket requester = new ZSocket(ZContextProvider.GlobalContext, ZSocketType.REQ))
                {
                    requester.Connect(address);
                    requester.Send(new ZFrame(BinarySerializer <ControlMessage> .ToByteArray(message)));

                    using (ZFrame reply = requester.ReceiveFrame())
                    {
                        ControlMessage rcvedMsg = BinarySerializer <ControlMessage> .ToObject(reply.Read());
                        succes = succes && rcvedMsg.Type.Equals(wantedType);
                    }
                }
            });

            return(succes);
        }