예제 #1
0
        /// <summary>
        /// 断掉连接,重新连接
        /// </summary>
        void ReconnectIfDis()
        {
            ///
            /// 超时处理
            ///
            isConnected = false;
            if (reqSock != null)
            {
                reqSock.Disconnect(ConnectingAddress);
                reqSock.Close();
            }

            ConsoleEx.DebugLog("HeartBeat socket is Connecting...", ConsoleEx.RED);

            var context = Core.ZeroMQ;

            reqSock = context.CreateRequestSocket();
            reqSock.Options.SendHighWatermark    = EngCfg.HighWatermark;
            reqSock.Options.ReceiveHighWatermark = EngCfg.HighWatermark;

            //生成通讯地址和协议方式
            ConnectingAddress = ConnectAddr(typeof(HeartBeatClient));
            reqSock.Connect(ConnectingAddress);

            isConnected = true;

            RepeatTimer.Change(IntervalPeriod, Timeout.Infinite);
        }
    protected override void Run()
    {
        ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet
        using (RequestSocket client = new RequestSocket())
        {
            client.Connect("tcp://localhost:5555");

            while (Running)
            {
                if (waitingForRequest != null)
                {
                    string message;
                    bool   gotMessage = client.TryReceiveFrameString(out message);
                    if (gotMessage)
                    {
                        waitingForRequest.image.RecieveResults(waitingForRequest.request, message);
                        waitingForRequest = null;
                    }
                }
                else if (requests.Count > 0)
                {
                    var request = requests.Dequeue();
                    client.SendFrame(request.request.HamiltonianString());
                    waitingForRequest = request;
                }
            }
        }

        NetMQConfig.Cleanup(); // this line is needed to prevent unity freeze after one use, not sure why yet
    }
예제 #3
0
        public Result GetRepositories(string query)
        {
            var watch = Stopwatch.StartNew();

            _answer       = null;
            _repositories = null;

            using (var client = new RequestSocket())
            {
                client.Connect(EndpointProvider.Address);

                byte[] load = Encoding.UTF8.GetBytes(query);
                client.SendFrame(load);
                client.ReceiveReady += ClientOnReceiveReady;

                client.Poll(TimeSpan.FromMilliseconds(3000));

                client.ReceiveReady -= ClientOnReceiveReady;
                client.Disconnect(EndpointProvider.Address);
            }

            watch.Stop();

            return(new Result()
            {
                Answer = _answer ?? GetErrorMessage(),
                DurationMilliseconds = watch.ElapsedMilliseconds,
                Repositories = _repositories ?? new Repository[0]
            });
        }
예제 #4
0
        public static T RequestSendReceive <T>(this RequestSocket socket, IdKeyData ikd)
        {
            try
            {
                lock (socket)
                {
                    socket.SendMoreFrame(ikd.Id).SendMoreFrame(ikd.Key).SendFrame(ikd.Data);

                    NetMQMessage msg = null;
#if DEBUG1
                    msg = socket.ReceiveMultipartMessage();  // debug模式打开,不会超时
#else
                    socket.TryReceiveMultipartMessage(TimeSpan.FromSeconds(10), ref msg);
#endif
                    if (msg != null)
                    {
                        var result = JsonUtil.Deserialize <T>(msg[0].Buffer);
                        return(result);
                    }
                    else
                    {
                        throw new Exception("中心服务器请求失败!");
                    }
                }
            }
            catch (Exception ex)
            {
                socket = new RequestSocket();
                socket.Connect(MQConfig.ResponseServer);

                LogUtil.Warn("RequestSendReceive 异常:" + ex.StackTrace);
                return(default(T));
            }
        }
예제 #5
0
    public override void Run()
    {
        ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use

        using (RequestSocket client = new RequestSocket())
        {
            client.Connect("tcp://localhost:5555");

            string signal     = "None";
            bool   gotMessage = false;

            //Debug.Log("----Sending Signal----");
            client.SendFrame(message);

            while (Running)
            {
                gotMessage = client.TryReceiveFrameString(out signal);                 // this returns true if it's successful
                if (gotMessage)
                {
                    break;
                }
            }

            if (gotMessage)
            {
                //Debug.Log("----Recived Signal: " + signal);
                EmotionInput.activeEmotion = signal;
                Running = false;
            }
        }
        NetMQConfig.Cleanup(); // this line is needed to prevent unity freeze after one use
    }
예제 #6
0
        private void OpeningWindow_Shown(object sender, EventArgs e)
        {
            //File Picker
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "c:\\Program Files (x86)\\Riftcat 2";
            openFileDialog1.Filter           = "VRidge|VRidge.exe";
            openFileDialog1.FilterIndex      = 2;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                var path = openFileDialog1.FileName;
            }

            //Start RiftCat
            System.Diagnostics.Process.Start(openFileDialog1.FileName);



            //Link With VRidge API
            System.Threading.Thread.Sleep(5000); //Let VRidge API Start
            var controlSocket = new RequestSocket();

            controlSocket.Connect("tcp://localhost:38219"); // use ip for remote connections

            //MessageBox.Show(string.Join("\n", "Linked With VRidge API"));  //Not 100% sure if this line is true yet, also i haven't preformed any checks to make sure that this message is accurate.
        }
    protected /*override*/ void Run2()
    {
        ForceDotNet.Force();
        using (RequestSocket client = new RequestSocket())
        {
            client.Connect("tcp://localhost:5555");

            while (running)
            {
                //Debug.Log("Sending Hello");
                //client.SendFrame("subject: " + subject.x + "; " + subject.y);
                client.SendFrame(JsonUtility.ToJson(subject));
                Debug.Log("Sent " + JsonUtility.ToJson(subject));

                string message    = null;
                bool   gotMessage = false;
                while (running)
                {
                    gotMessage = client.TryReceiveFrameString(out message);
                    if (gotMessage)
                    {
                        break;
                    }
                }

                if (gotMessage)
                {
                    Debug.Log("Received " + message);
                    UnityMainThreadDispatcher.Instance().Enqueue(HandleMessage(message));
                }
            }
        }

        NetMQConfig.Cleanup();
    }
예제 #8
0
        public void SendAndReceive()
        {
            using (var front = new RouterSocket())
                using (var back = new DealerSocket())
                {
                    front.Bind("inproc://frontend");
                    back.Bind("inproc://backend");

                    var proxy = new Proxy(front, back);
                    Task.Factory.StartNew(proxy.Start);

                    using (var client = new RequestSocket())
                        using (var server = new ResponseSocket())
                        {
                            client.Connect("inproc://frontend");
                            server.Connect("inproc://backend");

                            client.SendFrame("hello");
                            Assert.AreEqual("hello", server.ReceiveFrameString());
                            server.SendFrame("reply");
                            Assert.AreEqual("reply", client.ReceiveFrameString());
                        }

                    proxy.Stop();
                }
        }
예제 #9
0
        public void StartAndStopStateValidation()
        {
            using (var front = new RouterSocket())
                using (var back = new DealerSocket())
                {
                    front.Bind("inproc://frontend");
                    back.Bind("inproc://backend");

                    var proxy = new Proxy(front, back);
                    Task.Factory.StartNew(proxy.Start);

                    // Send a message through to ensure the proxy has started
                    using (var client = new RequestSocket())
                        using (var server = new ResponseSocket())
                        {
                            client.Connect("inproc://frontend");
                            server.Connect("inproc://backend");
                            client.SendFrame("hello");
                            Assert.AreEqual("hello", server.ReceiveFrameString());
                            server.SendFrame("reply");
                            Assert.AreEqual("reply", client.ReceiveFrameString());
                        }

                    Assert.Throws <InvalidOperationException>(proxy.Start);
                    Assert.Throws <InvalidOperationException>(proxy.Start);
                    Assert.Throws <InvalidOperationException>(proxy.Start);

                    proxy.Stop(); // blocks until stopped

                    Assert.Throws <InvalidOperationException>(proxy.Stop);
                }
        }
예제 #10
0
        public void Run()
        {
            IsRunning = true;

            try
            {
                using (var socket = new RequestSocket())
                {
                    socket.Options.Linger = TimeSpan.Zero;

                    socket.Connect(serverAddress.ZmqAddress + ":" + GlobalConstants.TcpIpPort.Request);

                    while (!stopRunning)
                    {
                        var workItem = workQueue.TimeoutTake();

                        if (workItem == null)                           // Timeout-case
                        {
                            continue;
                        }

                        workItem.HandleRequest(socket);
                    }
                }
            }
            catch
            {
                // ignored
            }

            IsRunning = false;
        }
예제 #11
0
파일: DataGetter.cs 프로젝트: jealford/VRM
    protected override void Run()
    {
        ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet
        using (RequestSocket client = new RequestSocket())
        {
            client.Connect("tcp://localhost:5555");

            while (Running)
            {
                Debug.Log("Request");
                if (isReady)
                {
                    client.SendFrame(makeAngleJSON());
                    string message    = null;
                    bool   gotMessage = false;
                    while (Running)
                    {
                        gotMessage = client.TryReceiveFrameString(out message); // this returns true if it's successful
                        if (gotMessage)
                        {
                            break;
                        }
                    }
                    if (gotMessage)
                    {
                        Debug.Log("Received " + message);
                        isReady = false;
                    }
                }
            }
        }

        NetMQConfig.Cleanup(); // this line is needed to prevent unity freeze after one use, not sure why yet
    }
예제 #12
0
        static void Main(string[] args)
        {
            Console.WriteLine("Client initilizing");

            using (var client = new RequestSocket())
            {
                client.Connect("tcp://localhost:5555");

                byte[] data = File.ReadAllBytes(path);

                var f1 = "FILE";
                var f2 = "testFileToSend.txt";
                var f3 = data;


                client.SendMoreFrame(f1).SendMoreFrame(f2).SendFrame(f3);


                Console.WriteLine("Frame 1:" + f1);
                Console.WriteLine("Frame 2:" + f2);
                Console.WriteLine("Frame 3 - length:" + f3.Length);

                Console.WriteLine("finished sending file");


                Console.ReadKey();
            }
        }
예제 #13
0
    void NetMQClient()
    {
        AsyncIO.ForceDotNet.Force();

        requestSocket = new RequestSocket();
        requestSocket.Connect("tcp://127.0.0.1:5555");

        while (!requestsCancelled)
        {
        }

        requestSocket.Close();
        NetMQConfig.Cleanup();

        //using (var reqSocket = new RequestSocket())
        //{
        //    reqSocket.Connect("tcp://127.0.0.1:5555");
        //    while (!requestsCancelled)
        //    {
        //        if (frame != null)
        //        {
        //            reqSocket.SendMoreFrame("F");
        //            string frameBase64 = System.Convert.ToBase64String(frame);
        //            reqSocket.SendFrame(frameBase64);

        //            var msg = reqSocket.ReceiveFrameString();
        //            print("From Server: " + msg);
        //        }
        //    }
        //    reqSocket.Close();
        //}
        //NetMQConfig.Cleanup();
    }
    private void ListenerWork()
    {
        AsyncIO.ForceDotNet.Force();
        using (var reqSocket = new RequestSocket())
        {
            string message = "";

            if (_brushStrokeIndex == "")
            {
                message = _message + "," + _picture;
            }

            else
            {
                message = _message + "," + _picture + "," + _brushStrokeIndex + ',' + _brushValues;
            }

            //reqSocket.Connect("tcp://192.168.0.6:12345");
            reqSocket.Connect("tcp://localhost:12345");
            reqSocket.SendFrame(message);

            string frameString = "";

            while (frameString == null || frameString.Equals(""))
            {
                if (!reqSocket.TryReceiveFrameString(out frameString))
                {
                }
                _messageQueue.Enqueue(frameString);
                _messageDelegate(frameString);
            }
            reqSocket.Close();
        }
        NetMQConfig.Cleanup();
    }
예제 #15
0
        private void StartQueryMQ()
        {
            this.Options = Options.LoadFromAppSettings();
            string serverAddress = System.Configuration.ConfigurationManager.AppSettings["AlyServerAddress"];
            string queryPort     = System.Configuration.ConfigurationManager.AppSettings["AlyServerQueryPort"];

            if (!string.IsNullOrEmpty(serverAddress) &&
                !string.IsNullOrEmpty(queryPort)
                )
            {
                string addressUrl = string.Format("tcp://{0}:{1}", serverAddress, queryPort);
                try
                {
                    if (null == _querySocket)
                    {
                        _querySocket = new RequestSocket();
                        _querySocket.ReceiveReady += _querySocket_ReceiveReady;
                        _querySocket.SendReady    += _querySocket_SendReady;
                    }

                    if (null == _queryPoller)
                    {
                        _queryPoller = new NetMQPoller();
                        _queryPoller.Add(_querySocket);
                        _querySocket.Connect(addressUrl);
                        _queryMsgList.Clear();
                        _queryPoller.RunAsync();
                        Console.WriteLine("[Progress]:[1] Request Listening");
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
예제 #16
0
        private void StartStationNetMQ()
        {
            try
            {
                _subscriber = new SubscriberSocket();
                _subscriber.ReceiveReady += _subscriber_ReceiveReady;
                //_fileSubscriber = new SubscriberSocket();
                _requester = new RequestSocket();
                _poller    = new NetMQPoller();

                IsLocalClient = CheckIsLocalIP(this.Options.ServerAddress);

                _subscriber.Connect(string.Format("tcp://{0}:{1}", this.Options.ServerAddress, this.Options.MsgPubPort));
                _subscriber.SubscribeToAnyTopic();
                _requester.Connect(string.Format("tcp://{0}:{1}", this.Options.ServerAddress, this.Options.MsgResPort));
                //_fileSubscriber.Connect(string.Format("tcp://{0}:{1}", this.Options.ServerAddress, this.Options.FilePubPort));
                //_fileSubscriber.SubscribeToAnyTopic();

                logger.InfoFormat("peripheral client netmq info: IP-{0},msg pub port:{1},msg res port:{2}", this.Options.ServerAddress, this.Options.MsgPubPort, this.Options.MsgResPort);

                // HockSocketEvents(true);

                //_poller.Add(_fileSubscriber);
                _poller.Add(_subscriber);
                _poller.Add(_requester);

                _poller.RunAsync();
                Console.WriteLine("[Progress]:[4] Sub Listening");

                // this.OnConnected();
            }
            catch (Exception ex)
            {
            }
        }
예제 #17
0
파일: Program.cs 프로젝트: cgath/Clara
        static void Main(string[] args)
        {
            using (var client = new RequestSocket())
            {
                client.Connect("tcp://localhost:5555");

                Console.WriteLine("Client connected to tcp://127.0.0.1:5555");
                Console.WriteLine("Press <Enter> to send request. Press <Esc> to quit.");

                ConsoleKeyInfo cki;
                while (true)
                {
                    cki = Console.ReadKey();
                    if (cki.Key == ConsoleKey.Enter)
                    {
                        client.SendFrame("Hello from client!");

                        var message = client.ReceiveFrameString();
                        Console.WriteLine("Recieved {0} from Server.", message);
                    }

                    if (cki.Key == ConsoleKey.Escape)
                    {
                        break;
                    }
                }
            }
        }
예제 #18
0
        static void Main(string[] args)
        {
            Console.WriteLine("NetMq hello wolrd client have started:");

            using (var client = new RequestSocket())
            {
                client.Connect("tcp://localhost:" + portToConnectTo);

                Console.WriteLine("Sending message, using 'A' as the first frame");


                client.SendMoreFrame("A").SendFrame("I am saying");

                var message = client.ReceiveFrameString();
                Console.WriteLine("Received {0}", message);

                Console.WriteLine("Sending message, using 'B' as the first frame");

                client.SendMoreFrame("B").SendFrame(", world!");

                message = client.ReceiveFrameString();
                Console.WriteLine("Received {0}", message);

                client.SendMoreFrame("C").SendFrame(", world!");

                message = client.ReceiveFrameString();
                Console.WriteLine("Received {0}", message);


                //waiting so the tester can see the console
                Console.ReadKey();
            }
        }
예제 #19
0
 public void CallDirectoryService()
 {
     ThreadPool.QueueUserWorkItem(state => {
         var req = new ServiceHostRequest()
         {
             Address = _ip, ServiceType = "render"
         };
         var dirServiceSocket = new RequestSocket();
         dirServiceSocket.Connect("tcp://" + _dirSerIp + ":8910");
         while (!_stopLoops)
         {
             try {
                 using (var reqStream = new MemoryStream()) {
                     Serializer.Serialize(reqStream, req);
                     dirServiceSocket.SendFrame(reqStream.ToArray());
                 }
                 var receiveFrame = dirServiceSocket.ReceiveFrameBytes();
                 var request      = Serializer.Deserialize <Message>(new MemoryStream(receiveFrame)) as BooleanResponse;
                 Console.WriteLine(request.Ok);
                 if (request.Ok)
                 {
                     return;
                 }
             } catch (Exception e) {
                 Console.WriteLine(e);
             }
             Thread.Sleep(900);
         }
     });
 }
예제 #20
0
        public async Task DoStart()
        {
            using (_worker = new RequestSocket())
            {
                _worker.Options.Identity = Id.ToByteArray();
                _worker.Connect(_configuration.GatewayEndpoint);

                while (!_isConnected.Value)
                {
                    Thread.Sleep(50);
                }

                _worker.SendFrame(CreateReadyEvent().Serialize());

                while (!_cancel.IsCancellationRequested)
                {
                    var work = _worker.ReceiveFrameBytes()
                               .Deserialize <TransportMessage>();

                    if (_cancel.IsCancellationRequested)
                    {
                        return;
                    }

                    var response = await CreateResponse(work);

                    _worker.SendFrame(response.Serialize());
                }
            }
        }
예제 #21
0
        /// <summary>
        ///     取得Socket对象
        /// </summary>
        /// <param name="type"></param>
        /// <param name="socket"></param>
        /// <returns></returns>
        private static bool GetSocket(string type, out RequestSocket socket)
        {
            try
            {
                lock (Publishers)
                {
                    if (Publishers.TryGetValue(type, out socket))
                    {
                        return(true);
                    }
                    var config = StationProgram.GetConfig(type);
                    if (config == null)
                    {
                        StationProgram.WriteLine($"【{type}】connect error =>无法拉取配置");
                        return(false);
                    }

                    socket = new RequestSocket();
                    socket.Options.Identity =
                        StationProgram.Config.StationName.ToAsciiBytes(); //RandomOperate.Generate(8).ToAsciiBytes();
                    socket.Options.ReconnectInterval = new TimeSpan(0, 0, 0, 0, 200);
                    socket.Connect(config.OutAddress);
                    Publishers.Add(type, socket);
                }
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                StationProgram.WriteLine($"【{type}】connect error =>连接时发生异常:{e}");
                socket = null;
                return(false);
            }

            return(true);
        }
예제 #22
0
        public void MonitorDisposeProperlyWhenDisposedAfterMonitoredTcpSocket()
        {
            // The bug:
            // Given we monitor a netmq tcp socket
            // Given we disposed of the monitored socket first
            // When we dispose of the monitor
            // Then our monitor is Faulted with a EndpointNotFoundException
            // And monitor can't be stopped or disposed

            using (var res = new ResponseSocket())
            {
                NetMQMonitor monitor;
                using (var req = new RequestSocket())
                {
                    monitor = new NetMQMonitor(req, "inproc://#monitor", SocketEvents.All);
                    Task.Factory.StartNew(monitor.Start);

                    // Bug only occurs when monitoring a tcp socket
                    var port = res.BindRandomPort("tcp://127.0.0.1");
                    req.Connect("tcp://127.0.0.1:" + port);

                    req.SendFrame("question");
                    Assert.That(res.ReceiveFrameString(), Is.EqualTo("question"));
                    res.SendFrame("response");
                    Assert.That(req.ReceiveFrameString(), Is.EqualTo("response"));
                }
                Thread.Sleep(100);
                // Monitor.Dispose should complete
                var completed = Task.Factory.StartNew(() => monitor.Dispose()).Wait(1000);
                Assert.That(completed, Is.True);
            }
            // NOTE If this test fails, it will hang because context.Dispose will block
        }
예제 #23
0
        public void ResponsePoll()
        {
            using (var rep = new ResponseSocket())
                using (var req = new RequestSocket())
                    using (var poller = new NetMQPoller {
                        rep
                    })
                    {
                        int port = rep.BindRandomPort("tcp://127.0.0.1");

                        req.Connect("tcp://127.0.0.1:" + port);

                        rep.ReceiveReady += (s, e) =>
                        {
                            bool more;
                            Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more));
                            Assert.False(more);

                            e.Socket.SendFrame("World");
                        };

                        poller.RunAsync();

                        req.SendFrame("Hello");

                        bool more2;
                        Assert.AreEqual("World", req.ReceiveFrameString(out more2));
                        Assert.IsFalse(more2);

                        poller.Stop();
                    }
        }
예제 #24
0
 public string SendMessageAndGetReply(string message)
 {
     using var client = new RequestSocket();
     client.Connect("tcp://127.0.0.1:" + Port);
     client.SendFrame(message);
     return(GetResponse(client, message));
 }
예제 #25
0
 // Start is called before the first frame update
 void Start()
 {
     ForceDotNet.Force();
     client = new RequestSocket();
     client.Connect("tcp://localhost:5555");
     Debug.Log("connected");
 }
예제 #26
0
        static void Main(string[] args)
        {
            Dictionary <string, List <string> > offerStorage = new Dictionary <string, List <string> >();

            Console.WriteLine("TypeClientAggregator");
            using (var server = new ResponseSocket())
                using (var emailer = new RequestSocket())
                {
                    server.Bind("tcp://*:5557");
                    emailer.Connect("tcp://127.0.0.1:5558");
                    while (true)
                    {
                        var message = server.ReceiveMultipartMessage(3);

                        Console.WriteLine("responseSocket : Server Received '{0}'-{1}", message[0].ConvertToString(Encoding.UTF8), message[1].ConvertToString(Encoding.UTF8));
                        string hashKey = GetHashString(message[0].ConvertToString(Encoding.UTF8) + message[1].ConvertToString(Encoding.UTF8));
                        if (offerStorage.ContainsKey(hashKey))
                        {
                            offerStorage[hashKey].Add(message[2].ConvertToString(Encoding.UTF8));
                            if (offerStorage[hashKey].Count >= 3)
                            {
                                mailOffer(emailer, message[0].ConvertToString(Encoding.UTF8), message[1].ConvertToString(Encoding.UTF8), offerStorage[hashKey]);
                                offerStorage.Remove(hashKey);
                            }
                        }
                        else
                        {
                            offerStorage.Add(hashKey, new List <string>());
                            offerStorage[hashKey].Add(message[2].ConvertToString(Encoding.UTF8));
                        }
                        server.SendFrameEmpty();
                    }
                }
        }
예제 #27
0
        static void RunClient(CancellationToken cancellationToken)
        {
            Task.Factory.StartNew(() =>
            {
                using (var client = new RequestSocket())
                {
                    client.Connect("tcp://localhost:5555");
                    var i = 0;

                    while (true)
                    {
                        Console.WriteLine("Client: Sending Hello");

                        var request = new NetMQMessage();
                        request.Append($"Hello {i++}");
                        request.AppendEmptyFrame();

                        client.SendMultipartMessage(request);

                        var response = client.ReceiveMultipartMessage();
                        var message  = response[0].ConvertToString();

                        Console.WriteLine($"Client: Received {message}");

                        if (cancellationToken.IsCancellationRequested)
                        {
                            return;
                        }
                    }
                }
            });
        }
예제 #28
0
        public void Start()
        {
            using (_worker = new RequestSocket())
            {
                _worker.Connect(_loadBalancerEndpoint);

                var ready = new Work()
                {
                    Status = WorkerStatus.Ready
                };

                var readyBytes = ready.Serialize();

                _worker.SendFrame(readyBytes);

                while (!_cancel.IsCancellationRequested)
                {
                    var workBytes = _worker.ReceiveFrameBytes();
                    var work      = JsonConvert.DeserializeObject <Work>(Encoding.UTF8.GetString(workBytes));
                    work.Status = WorkerStatus.Finished;
                    Thread.Sleep(100);
                    var messageBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(work));
                    _worker.SendFrame(messageBytes);
                }
            }
        }
예제 #29
0
    protected override void Run()
    {
        ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet
        using (RequestSocket client = new RequestSocket())
        {
            //client.Connect("tcp://localhost:5555");
            client.Connect("tcp://192.168.1.191:5566");
            while (Running)
            {
                //Debug.Log("Sending Hello");
                client.SendFrame("Hello");
                string message    = null;
                bool   gotMessage = false;
                while (Running)
                {
                    gotMessage = client.TryReceiveFrameString(out message); // this returns true if it's successful
                    if (gotMessage)
                    {
                        break;
                    }
                }

                if (gotMessage)
                {
                    //Debug.Log("Received " + message);
                    callback(message);
                }
            }
        }

        NetMQConfig.Cleanup(); // this line is needed to prevent unity freeze after one use, not sure why yet
    }
예제 #30
0
        public void RequestMessage()
        {
            var messageReceived = false;
            var message         = "";

            AsyncIO.ForceDotNet.Force();

            var timeout = new TimeSpan(0, 0, 2);

            using (var socket = new RequestSocket())
            {
                socket.Connect($"tcp://{_host}:{_port}");
                if (socket.TrySendFrame("Hello"))
                {
                    messageReceived = socket.TryReceiveFrameString(timeout, out message);
                }
            }

            NetMQConfig.Cleanup();
            if (!messageReceived)
            {
                message = "Could not receive message from server!";
            }
            _messageCallback(message);
        }
예제 #31
0
파일: Program.cs 프로젝트: GrabCAD/netmq
        private static RequestSocket CreateServerSocket()
        {
            Console.WriteLine("C: Connecting to server...");

            var client = new RequestSocket();
            client.Connect(ServerEndpoint);
            client.Options.Linger = TimeSpan.Zero;
            client.ReceiveReady += ClientOnReceiveReady;

            return client;
        }
예제 #32
0
파일: Program.cs 프로젝트: cjkao/netmq
        private static int Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("usage: remote_lat remote_lat <connect-to> <message-size> <roundtrip-count>");
                return 1;
            }

            string connectTo = args[0];
            int messageSize = int.Parse(args[1]);
            int roundtripCount = int.Parse(args[2]);

            using (var req = new RequestSocket())
            {
                req.Connect(connectTo);

                var msg = new Msg();
                msg.InitPool(messageSize);

                var stopWatch = Stopwatch.StartNew();

                for (int i = 0; i != roundtripCount; i++)
                {
                    req.Send(ref msg, more: false);

                    req.Receive(ref msg);

                    if (msg.Size != messageSize)
                    {
                        Console.WriteLine("message of incorrect size received. Received: {0} Expected: {1}", msg.Size, messageSize);
                        return -1;
                    }
                }

                stopWatch.Stop();

                msg.Close();

                double elapsedMicroseconds = stopWatch.ElapsedTicks*1000000L/Stopwatch.Frequency;
                double latency = elapsedMicroseconds/(roundtripCount*2);

                Console.WriteLine("message size: {0} [B]", messageSize);
                Console.WriteLine("roundtrip count: {0}", roundtripCount);
                Console.WriteLine("average latency: {0:0.000} [µs]", latency);
            }

            return 0;
        }
예제 #33
0
파일: Program.cs 프로젝트: GrabCAD/netmq
        private static void Main()
        {
            using (var worker = new RequestSocket())
            {
                var random = new Random(DateTime.Now.Millisecond);
                var guid = Guid.NewGuid();

                worker.Options.Identity = Encoding.Unicode.GetBytes(guid.ToString());
                worker.Connect(ServerEndpoint);

                worker.ReceiveReady += (s, e) =>
                {
                    // Read and save all frames until we get an empty frame
                    // In this example there is only 1 but it could be more
                    byte[] address = worker.ReceiveFrameBytes();
                    worker.ReceiveFrameBytes(); // empty
                    byte[] request = worker.ReceiveFrameBytes();

                    worker.SendMoreFrame(address);
                    worker.SendMoreFrame(Encoding.Unicode.GetBytes(""));
                    worker.SendFrame(Encoding.Unicode.GetBytes(Encoding.Unicode.GetString(request) + " WORLD!"));
                };

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

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

                    worker.Poll(TimeSpan.FromMilliseconds(1000));
                }
            }
        }
예제 #34
0
파일: Program.cs 프로젝트: GrabCAD/netmq
        private static bool TryRequest(string endpoint, string requestString)
        {
            Console.WriteLine("Trying echo service at {0}", endpoint);

            using (var client = new RequestSocket())
            {
                client.Options.Linger = TimeSpan.Zero;

                client.Connect(endpoint);

                client.SendFrame(requestString);
                client.ReceiveReady += ClientOnReceiveReady;
                bool pollResult = client.Poll(TimeSpan.FromMilliseconds(RequestTimeout));
                client.ReceiveReady -= ClientOnReceiveReady;
                client.Disconnect(endpoint);
                return pollResult;
            }
        }
예제 #35
0
파일: Program.cs 프로젝트: cjkao/netmq
        private static RequestSocket CreateServerSocket()
        {
            Console.WriteLine("C: Connecting to server...");

            var guid = Guid.NewGuid();
            var client = new RequestSocket
            {
                Options =
                {
                    Linger = TimeSpan.Zero,
                    Identity = Encoding.Unicode.GetBytes(guid.ToString())
                }
            };
            client.Connect(ServerEndpoint);
            client.ReceiveReady += ClientOnReceiveReady;

            return client;
        }
예제 #36
0
파일: Worker.cs 프로젝트: cjkao/netmq
        public void Run()
        {
            var rnd = new Random(m_id);

            using (var worker = new RequestSocket())
            {
                worker.Connect(m_localBackendAddress);

                Console.WriteLine("[WORKER {0}] Connected & READY", m_id);

                // build READY message
                var msg = new NetMQMessage();
                var ready = NetMQFrame.Copy(new[] { Program.WorkerReady });

                msg.Append(ready);
                msg.Push(NetMQFrame.Empty);
                msg.Push(new[] { m_id });

                // and send to broker
                worker.SendMultipartMessage(msg);

                while (true)
                {
                    // wait for a request - the REQ might be from a local client or a cloud request
                    var request = worker.ReceiveMultipartMessage();

                    if (request.FrameCount < 3)
                    {
                        Console.WriteLine("[WORKER {0}] ERR - received an empty message", m_id);
                        break; // something went wrong -> exit
                    }

                    Console.WriteLine("[WORKER {0}] received", m_id);

                    foreach (var frame in request)
                        Console.WriteLine("\t[{0}", frame.ConvertToString());

                    // simulate working for an arbitrary time < 2s
                    Thread.Sleep(rnd.Next(2000));
                    // simply send back what we received
                    worker.SendMultipartMessage(request);
                }
            }
        }
예제 #37
0
파일: Program.cs 프로젝트: GrabCAD/netmq
        private static void WorkerTask(object portNumber)
        {
            var random = new Random(DateTime.Now.Millisecond);

            using (var worker = new RequestSocket())
            {
                // We use a string identity for ease here
                string id = ZHelpers.SetID(worker, Encoding.Unicode);
                string cnn = $"tcp://localhost:{portNumber}";
                worker.Connect(cnn);
                Console.WriteLine("[W] ID {0} connect to {1}", id, cnn);

                int total = 0;

                bool end = false;
                while (!end)
                {
                    // Tell the router we're ready for work
                    worker.SendFrame("Ready");
                    //Console.WriteLine("[W] Message sent: {0}", msg);

                    // Get workload from router, until finished
                    string workload = worker.ReceiveFrameString();
                    //Console.WriteLine("[W] Workload received: {0}", workload);

                    if (workload == "END")
                    {
                        end = true;
                    }
                    else
                    {
                        total++;

                        Thread.Sleep(random.Next(1, 1000)); //  Simulate 'work'
                    }
                }

                Console.WriteLine("ID ({0}) processed: {1} tasks", Encoding.Unicode.GetString(worker.Options.Identity), total);
            }
        }
예제 #38
0
파일: Program.cs 프로젝트: hdxhan/netmq
        private static void ClientRoutine(object clientId)
        {
            try
            {
                using (var req = new RequestSocket())
                {
                    req.Connect("tcp://localhost:5555");

                    byte[] message = Encoding.Unicode.GetBytes(string.Format("{0} Hello", clientId));

                    Console.WriteLine("Client {0} sent \"{0} Hello\"", clientId);
                    req.SendFrame(message, message.Length);

                    var response = req.ReceiveFrameString(Encoding.Unicode);
                    Console.WriteLine("Client {0} received \"{1}\"", clientId, response);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception on ClientRoutine: {0}", ex.Message);
            }
        }
예제 #39
0
    public void Init(string hostAddress, string portNumber, string portNumber_info, bool shouldCreateTestClient, bool shouldCreateServer, bool debugNetworkMessages,
		bool logSimpleTimingInfo, bool logDetailedTimeInfo, string preferredImageFormat, bool saveDebugImageFiles, string environmentScene)
    {
        this.avatarPrefab = Resources.Load<Avatar>("Prefabs/Avatar");
        if (this.avatarPrefab == null) {
            Debug.Log ("it doesnt exist still!");
        }
        Debug.Log ("May have just printed something right here^");

        Debug.Log (this.avatarPrefab.name);

        // Read port number
        this.portNumber = portNumber;
                this.portNumber_info = portNumber_info;
        this.hostAddress = hostAddress;
        this.shouldCreateTestClient = shouldCreateTestClient;
        this.shouldCreateServer = shouldCreateServer;
        this.debugNetworkMessages = debugNetworkMessages;
        logSimpleTimeInfo = logSimpleTimingInfo;
        logTimingInfo = logDetailedTimeInfo;
        CameraStreamer.preferredImageFormat = preferredImageFormat; // defaults to bmp
        this.saveDebugImageFiles = saveDebugImageFiles; // defaults to False
        this.environmentScene = environmentScene; // defaults to "Empty"

        // Load Environment Scene
        if (shouldCreateServer) {
            SceneManager.LoadScene (environmentScene, LoadSceneMode.Additive);
            if (!SceneManager.GetSceneByName (environmentScene).IsValid()) {
                Debug.LogWarning ("Scene name \"" + environmentScene + "\" was not found.");
            }
        }

        // Start up connections
        _ctx = NetMQContext.Create();
        clientInfo = _ctx.CreateRequestSocket();
        clientInfo.Options.Linger = TimeSpan.Zero;
        clientInfo.Connect("tcp://" + hostAddress + ":" + portNumber_info);
        CreateNewSocketConnection();

        Debug.Log ("Net Messenger Initialized!");
    }
예제 #40
0
파일: Client.cs 프로젝트: hdxhan/netmq
        public void Run()
        {
            Console.WriteLine("[CLIENT {0}] Starting", m_id);

            var rnd = new Random(m_id);
            // each request shall have an unique id in order to recognize an reply for a request
            var messageId = new byte[5];
            // create clientId for messages
            var clientId = new[] { m_id };
            // a flag to signal that an answer has arrived
            bool messageAnswered = false;
            // we use a poller because we have a socket and a timer to monitor
            using (var clientPoller = new NetMQPoller())
            using (var client = new RequestSocket())
            using (var monitor = new PushSocket())
            {
                client.Connect(m_localFrontendAddress);
                monitor.Connect(m_monitorAddress);

                client.Options.Identity = new[] { m_id };
                var timer = new NetMQTimer((int)TimeSpan.FromSeconds(10).TotalMilliseconds);

                // use as flag to indicate exit
                var exit = false;

                // every 10 s check if message has been received, if not then send error message and ext
                // and restart timer otherwise
                timer.Elapsed += (s, e) =>
                {
                    if (messageAnswered)
                    {
                        e.Timer.Enable = true;
                    }
                    else
                    {
                        var msg = string.Format("[CLIENT {0}] ERR - EXIT - lost message {1}", m_id, messageId);
                        // send an error message
                        monitor.SendFrame(msg);

                        // if poller is started than stop it
                        if (clientPoller.IsRunning)
                            clientPoller.Stop();
                        // mark the required exit
                        exit = true;
                    }
                };

                // process arriving answers
                client.ReceiveReady += (s, e) =>
                {
                    // mark the arrival of an answer
                    messageAnswered = true;
                    // worker is supposed to answer with our request id
                    var reply = e.Socket.ReceiveMultipartMessage();

                    if (reply.FrameCount == 0)
                    {
                        // something went wrong
                        monitor.SendFrame(string.Format("[CLIENT {0}] Received an empty message!", m_id));
                        // mark the exit flag to ensure the exit
                        exit = true;
                    }
                    else
                    {
                        var sb = new StringBuilder();

                        // create success message
                        foreach (var frame in reply)
                            sb.Append("[" + frame.ConvertToString() + "]");

                        // send the success message
                        monitor.SendFrame(string.Format("[CLIENT {0}] Received answer {1}",
                            m_id,
                            sb.ToString()));
                    }
                };

                // add socket & timer to poller
                clientPoller.Add(client);
                clientPoller.Add(timer);

                // start poller in another thread to allow the continued processing
                clientPoller.RunAsync();

                // if true the message has been answered
                // the 0th message is always answered
                messageAnswered = true;

                while (!exit)
                {
                    // simulate sporadic activity by randomly delaying
                    Thread.Sleep((int)TimeSpan.FromSeconds(rnd.Next(5)).TotalMilliseconds);

                    // only send next message if the previous one has been replied to
                    if (messageAnswered)
                    {
                        // generate random 5 byte as identity for for the message
                        rnd.NextBytes(messageId);

                        messageAnswered = false;

                        // create message [client adr][empty][message id] and send it
                        var msg = new NetMQMessage();

                        msg.Push(messageId);
                        msg.Push(NetMQFrame.Empty);
                        msg.Push(clientId);

                        client.SendMultipartMessage(msg);
                    }
                }

                // stop poller if needed
                if (clientPoller.IsRunning)
                    clientPoller.Stop();
            }
        }
예제 #41
0
    protected override void WritePort(byte[] buffer, int i, int length, string hwaddress)
    {
      try
      {
        byte[] data;

        if (i > 0)
        {
          data = new byte[length];
          Array.Copy(buffer, 0, data, 0, length);
        }
        else
        {
          data = buffer;
        }

        var req = new RequestSocket();

        req.Connect(_endpoint);

        req.SendFrame(data);

        while (req.HasOut)
          Thread.Sleep(500);

        Log.Debug(string.Format("PortZMq.WritePort: " + length + " bytes sent to " + _endpoint));
      }
      catch (Exception ex)
      {
        Log.Error("PortZMq.WritePort: failed sending buffer", ex);
        throw;
      }
    }
예제 #42
0
파일: Program.cs 프로젝트: GrabCAD/netmq
        /// <summary>
        ///     just to create the REQ socket
        /// </summary>
        /// <param name="id">the name for the client</param>
        /// <returns>the connected REQ socket</returns>
        private static RequestSocket CreateSocket(string id)
        {
            var client = new RequestSocket
            {
                Options =
                {
                    Identity = Encoding.UTF8.GetBytes(id),
                    Linger = TimeSpan.Zero
                }
            };

            // set the event to be called upon arrival of a message
            client.ReceiveReady += OnClientReceiveReady;
            client.Connect(Commons.QueueFrontend);

            return client;
        }