Exemple #1
0
        private void Worker(object sender, DoWorkEventArgs e)
        {
            try
            {
                using (var server = new ResponseSocket())
                {
                    server.Bind($"tcp://*:{e.Argument}");

                    while (true)
                    {
                        if (_worker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }

                        var message = server.ReceiveFrameString();
                        LogEvent?.Invoke(2, $"Received {message}");
                        //await Task.Delay(100);
                        LogEvent?.Invoke(2, "Sending World");
                        server.SendFrame("World");
                        //await Task.Delay(100);
                    }
                }
            }
            catch (Exception ex)
            {
                LogEvent?.Invoke(3, ex.Message);
            }
        }
Exemple #2
0
        public void TestServerReceiveReply()
        {
            //
            // Hello World server
            //
            //rtbStatus.AppendText("Server started");

            // Create
            using (var responder = new ResponseSocket())
            {
                // Bind
                responder.Bind("tcp://*:5555");

                while (true)
                {
                    // Receive
                    //Msg MyMessage;
                    //TimeSpan timeout = new TimeSpan(60000);
                    var message = responder.ReceiveFrameString();
                    // rtbStatus.AppendText("Received " + message);

                    // Do some work
                    Thread.Sleep(1000);

                    // Send
                    responder.SendFrame("Hello from C#: " + message);
                }
            }
        }
        public void HelloWorld()
        {
            var          timer    = new Timer(60000);
            const string endpoint = "tcp://PC_ip:4505";

            //10.151.111.166       12.207.170.27
            timer.Start();
            timer.Elapsed += (sender, args) =>
            {
                timer.Stop();
                Cancel = true;
            };

            using (var replierSocket = new ResponseSocket())
            {
                replierSocket.Connect(endpoint);
                Thread.Sleep(2000);
                while (true)
                {
                    var replyFromRequester = replierSocket.ReceiveFrameString();
                    Debug.WriteLine("Got reply " + replyFromRequester);
                    replierSocket.SendFrame("Response socket say hello");
                }
            }
        }
Exemple #4
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            using var server = new ResponseSocket("tcp://*:8050");


            while (!stoppingToken.IsCancellationRequested)
            {
                string serverMessage = "";
                await Task.Run(() =>
                {
                    try
                    {
                        serverMessage = server.ReceiveFrameString();
                        Console.WriteLine($"Client Sent: {serverMessage} DateTime: {DateTime.Now}");
                        Console.WriteLine("Sending reply to the client ...");

                        const string msg1 = "Hi", msg2 = "How are you ?";

                        var response = new NetMQMessage();
                        response.Append(msg1);
                        response.Append(msg2);

                        server.SendMultipartMessage(response);
                        Console.WriteLine($"Response has been sent => 1: {msg1}, 2: {msg2}");

                        _hubContext.Clients.All.SendAsync("ReceiveNotification", serverMessage);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error: {ex.Message} DateTime: {DateTime.Now}");
                    }
                });
            }
        }
Exemple #5
0
        static void Main()
        {
            PrimeNumbers[2] = null;
            PrimeNumbers[3] = null;

            using (var server = new ResponseSocket("@tcp://localhost:5556"))
            {
                string msg;
                do
                {
                    msg = server.ReceiveFrameString();
                    Console.WriteLine($"From Client: {msg}");

                    if (!uint.TryParse(msg, out uint number))
                    {
                        server.SendFrame($"{msg} is not a number!");
                        continue;
                    }

                    if (number == 1)
                    {
                        server.SendFrame("One is not a prime.");
                        continue;
                    }

                    var primeFactors = PrimeFactorsOf(number);
                    // Send a response back from the server
                    server.SendFrame(primeFactors);
                } while (msg != "done");
            }
        }
Exemple #6
0
        void Work()
        {
            new Thread(() =>
            {
                JToken jt_result = new JObject();

                //Transfer();
                using (var server = new ResponseSocket())
                {
                    server.Bind("tcp://*:592");

                    while (true)
                    {
                        var message = server.ReceiveFrameString().Trim('@', '$');

                        var jt_req = JsonConvert.DeserializeObject <JObject>(message);

                        Dispatcher.Invoke(() => { textblock_msg.Text += message + "\r\n"; });

                        jt_result = Transfer(jt_req["d"]);

                        string feedbackMsg = JsonConvert.SerializeObject(jt_result);

                        server.SendFrame(feedbackMsg);
                    }
                }
            }
                       )
            {
                IsBackground = true
            }.Start();
        }
Exemple #7
0
        public static void Main(string[] args)
        {
            using (var server = new ResponseSocket("@tcp://localhost:5556"))
                using (var client = new RequestSocket(">tcp://localhost:5556"))
                {
                    Console.WriteLine("Unesite nick");

                    var nick = Console.ReadLine();
                    while (true)
                    {
                        Console.WriteLine("Unesite poruku");
                        var     messageContent = Console.ReadLine();
                        Message message        = new Message(nick, messageContent);
                        client.SendFrame(message.ToString());

                        string   m1       = server.ReceiveFrameString();
                        string[] nickname = m1.Split(',');
                        Console.WriteLine("From Client: {0},message: {1}", nickname[0], nickname[1]);

                        server.SendFrame("Hi " + nickname[0]);

                        string m2 = client.ReceiveFrameString();
                        Console.WriteLine("From Server: {0}", m2);
                    }
                }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            using (var server = new ResponseSocket())
            {
                server.Bind("tcp://*:5555");

                while (true)
                {
                    var message = server.ReceiveFrameString();

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

                    if (message == "powerpcoff")
                    {
                        var psi = new ProcessStartInfo("shutdown", "/s /t 30");
                        psi.CreateNoWindow  = true;
                        psi.UseShellExecute = false;
                        Process.Start(psi);
                        server.SendFrame("ok");
                    }
                    ;

                    if (message == "tw")
                    {
                        Process.Start("C:\\Program Files (x86)\\TeamViewer\\TeamViewer.exe");
                        server.SendFrame("ok");
                    }
                    else  // В любом ином случае
                    {
                        Console.WriteLine("ok");
                        server.SendFrame("ok");
                    };
                }
            }
        }
Exemple #9
0
        static async Task Main(string[] args)
        {
            using (var responseSocket = new ResponseSocket("tcp://*:5555"))
                using (var requestSocket = new RequestSocket("tcp://localhost:5555"))
                {
                    Console.WriteLine("requestSocket : Sending 'Hello'");
                    requestSocket.SendFrame("Hello");
                    var message = responseSocket.ReceiveFrameString();
                    Console.WriteLine("responseSocket : Server Received '{0}'", message);
                    Console.WriteLine("responseSocket Sending 'World'");
                    responseSocket.SendFrame("World");
                    message = requestSocket.ReceiveFrameString();
                    Console.WriteLine("requestSocket : Received '{0}'", message);
                    Console.ReadLine();
                }

            Console.WriteLine("ZeroMQ intra-app communications demo");
            Console.WriteLine("Use CTRL+C shortcut to cancel at any time");

            var echoServerTask      = EchoServer();
            var streamTask          = StreamServer();
            var streamToConsoleTask = PushStreamToConsole();
            var consoleToEchoTask   = RelayConsoleToEchoServer();


            await Task.WhenAll(echoServerTask, streamTask, streamToConsoleTask, consoleToEchoTask);
        }
Exemple #10
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
        }
Exemple #11
0
        public async Task RespondAsync(Func <ContextModel, Task <OperationResult> > response)
        {
            UiOperationResult uiResult = null;

            try
            {
                var          contextModel = _socket.ReceiveFrameString();
                ContextModel model        = JsonConvert.DeserializeObject <ContextModel>(contextModel);
                if (model.User == null)
                {
                    throw new InvalidOperationException($"input: {contextModel} ain`t no ContextModel");
                }
                var opResult = await response(model);

                uiResult = FromOperationResult(opResult);
            }
            catch (System.Exception ex)
            {
                var oR = OperationResult.Failure
                         (
                    ResultType.BadRequest,
                    $"could not parse contextModel: {ex.Message}"
                         );
                uiResult = FromOperationResult(oR);
            }

            string json = JsonConvert.SerializeObject(uiResult);

            byte[] bytes = Encoding.UTF8.GetBytes(json);
            _socket.SendFrame(bytes);
        }
Exemple #12
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();
                }
        }
Exemple #13
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);
                }
        }
Exemple #14
0
        public static async Task Main(string[] args)
        {
            var listenPort = ushort.Parse(args[0]);

            var seeds  = args.Skip(1).Select(Utils.IPEndPointFromString).ToArray();
            var logger = Utils.CreateLogger <Program>();

            var gossiper = await StartGossiper(listenPort, seeds, logger);

            using (var response = new ResponseSocket())
            {
                string address = "0.0.0.0";

                Console.WriteLine("Binding tcp://{0}:{1}", address, listenPort);
                response.Bind($"tcp://{address}:{listenPort}");

                while (true)
                {
                    bool   hasMore;
                    string msg = response.ReceiveFrameString(out hasMore);

                    Console.WriteLine("Msg received! {0}", msg);
                    response.SendFrame(msg, hasMore);
                }
            }
        }
Exemple #15
0
        public static void RunServer()
        {
            using (NetMQSocket serverSocket = new ResponseSocket())
            {
                serverSocket.Bind("tcp://127.0.0.1:5555");
                while (true)
                {
                    string message1 = serverSocket.ReceiveFrameString();

                    Console.WriteLine("Receive message :\r\n{0}\r\n", message1);

                    string[] msg     = message1.Split(':');
                    string   message = msg[1];


                    #region 根据接收到的消息,返回不同的信息
                    if (message == "Hello")
                    {
                        serverSocket.SendFrame("World");
                    }
                    else
                    {
                        serverSocket.SendFrame(message);
                    }
                    #endregion

                    if (message == "exit")
                    {
                        break;
                    }
                }
            }
        }
Exemple #16
0
        static void Main(string[] args)
        {
            string connectionString = args[0];

            using (var send = new PushSocket(">tcp://127.0.0.1:9999"))
                using (var receive = new ResponseSocket(connectionString))
                {
                    while (true)
                    {
                        // Block for request
                        var message = receive.ReceiveFrameString();
                        var msgId   = Guid.NewGuid().ToString();

                        // Acknowledge
                        receive.SendFrame("200, ACK");

                        // Do Work ...
                        Thread.Sleep(2000);

                        // Send response
                        send.SendFrame(string.Format("Handler {0} completed task {1}",
                                                     connectionString, msgId));

                        // Exit handler
                        break;
                    }
                }
        }
Exemple #17
0
        void Listen()
        {
            using (var server = new ResponseSocket())
            {
                server.Bind($"tcp://*:{PORT}");

                while (!_Stopping)
                {
                    var message = server.ReceiveFrameString();

                    var sendContractPayload = JsonConvert.DeserializeObject <SendContractPayload>(message);

                    try
                    {
                        _App.SendContract(sendContractPayload.ContractHash, sendContractPayload.Data);
                        server.SendFrame("success");
                    }
                    catch (Exception e)
                    {
                        server.SendFrame("error");
                        Console.WriteLine("error: " + e.Message);
                    }
                }
            }
        }
Exemple #18
0
        static void Main(string[] args)
        {
            // Create context and socket
            using (var server = new ResponseSocket())
            {
                string bindPoint = "tcp://*:5555";
                server.Bind(bindPoint);

                Console.WriteLine("Server listening on {0}", bindPoint);
                Console.WriteLine("press <Esc> to quit.");

                do
                {
                    while (!Console.KeyAvailable)
                    {
                        // Wait for next request from client
                        string message = server.ReceiveFrameString();
                        Console.WriteLine("Recieved message: {0}", message);

                        // Do Work
                        Thread.Sleep(1000);

                        // Send reply back through socket
                        server.SendFrame("Hello from the Calibrator!");
                    }
                } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
            }
        }
Exemple #19
0
        public static void Main()
        {
            var obj = new RootObject();

            /*obj.items = new List<Factura>
             *            {
             *               new Factura {id_producto = 1, id_cliente = 12345678, nombre = "Joel", cantidad = 2, diferencia = 5 },
             *               new Factura {id_producto = 2, id_cliente = 12345678, nombre = "Joel", cantidad = 2, diferencia = 5 }
             *            };
             */
            /*var jeison = new Json
             * {
             *  id_producto = 1,
             *  id_cliente = 12345678,
             *  nombre = "Joel",
             *  cantidad = 2,
             *  diferencia = 5
             * };*/

            // string json = JsonConvert.SerializeObject(obj);

            using (var responder = new ResponseSocket())
            {
                responder.Bind("tcp://*:2104");

                while (true)
                {
                    string str = responder.ReceiveFrameString();
                    Console.WriteLine(str);
                    //Console.WriteLine("Received Hello");
                    Thread.Sleep(1000);  //  Do some 'work'
                    responder.SendFrame("Recibido por CuentasxCobrar");
                }
            }
        }
Exemple #20
0
        static void Main(string[] args)
        {
            var rand = new Random();

            while (true)
            {
                // specify one ephemeral port
                int    port    = rand.Next(49152, 65535);
                string address = $"tcp://*****:*****@{address}"))
                        using (var client = new RequestSocket($">{address}"))
                        {
                            while (true)
                            {
                                client.SendFrame("Hello");
                                Console.WriteLine($"From client: {server.ReceiveFrameString()}");

                                server.SendFrame("Hi Back");
                                Console.WriteLine($"From server: {client.ReceiveFrameString()}");

                                Thread.Sleep(1000);
                            }
                        }
                }
                catch (AddressAlreadyInUseException)
                {
                    Console.WriteLine($"This address is in use. Let's pick onther one.");
                }
            }
        }
Exemple #21
0
        public void setupServer()
        {
            using (var server = new ResponseSocket())
            {
                server.Bind("tcp://*:5555");
                while (true)
                {
                    var message = server.ReceiveFrameString();
                    Console.WriteLine(" Message Received on Server {0}", message);
                    Thread.Sleep(200);
                    server.SendFrame("World");
                    Console.WriteLine(" This is master changes that i need in feature branch");
                    Console.WriteLine(" BRanch changes ");
                    Console.WriteLine(" This is master changes that i need in feature branch +1 ");
                    Console.WriteLine(" This is master changes that i need in feature branch +2");
                    Console.WriteLine(" This is master changes that i need in feature branch +3");
                    Console.WriteLine(" This is master changes that i need in feature branch +4");

                    Console.WriteLine(" This is master changes that i need in feature branch +5");
                    Console.WriteLine(" This is master changes that i need in feature branch +4");
                    Console.WriteLine(" This is master changes that i need in feature branch +6");
                    Console.WriteLine(" This is master changes that i need in feature branch +7");

                    Console.WriteLine(" This is master changes that i need in feature branch +8");
                    Console.WriteLine(" This is master changes that i need in feature branch +9");


                    Console.WriteLine(" BRanch changes ");
                }
            }
        }
Exemple #22
0
        static void Main(string[] args)
        {
            int port = 5555;

            if (args.Length > 1)
            {
                int.TryParse(args[0], out port);
            }

            Console.WriteLine($"Starting NetMQ at TCP port {port}.");
            Console.WriteLine("Press CTRL+C to stop the service.");

            try
            {
                using (var server = new ResponseSocket())
                {
                    server.Bind($"tcp://*:{port}");
                    while (true)
                    {
                        var message = server.ReceiveFrameString();
                        Console.WriteLine(message);
                        Thread.Sleep(100);
                        server.SendFrame("***Processed***");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                Console.WriteLine("An unexpected error occurred.");
            }
        }
 private void Recv()
 {
     while (true)
     {
         bool more;
         var  msgType = server.ReceiveFrameString(out more);
         if (more)
         {
             var msg = server.ReceiveFrameString(out more);
             innerq.Enqueue(new Tuple <string, string>(msgType, msg));
             server.SendFrame("ACK");
         }
         else
         {
             server.SendFrame("NACK");
         }
     }
 }
Exemple #24
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello From Mars!");
            using var socket = new ResponseSocket("@tcp://localhost:5500");

            var msg = socket.ReceiveFrameString();

            Console.WriteLine($"From Earth : {msg}");
        }
Exemple #25
0
 private static void Main()
 {
     using (var server = new ResponseSocket("@tcp://*:11000"))
     {
         // the server receives, then sends
         Console.WriteLine("From Client: {0}", server.ReceiveFrameString());
         server.SendFrame("Hi Back");
         Console.ReadKey();
     }
 }
        public string Request(string request)
        {
            _con.Write("request  : ");
            _con.WriteLine(_reqColor, request);
            _socket.SendFrame(request);
            var response = _socket.ReceiveFrameString();

            _con.WriteLine(_resColor, response);
            return(response);
        }
Exemple #27
0
 private static void TestNetMq()
 {
     using (var server = new ResponseSocket())
     {
         server.Bind("tcp://*:5555");
         string msg = server.ReceiveFrameString();
         Console.WriteLine("From Client: {0}", msg);
         server.SendFrame("World");
     }
 }
Exemple #28
0
 public static string ReceiveAuthResponse()
 {
     // Start websocket server and listen for message
     using (var server = new ResponseSocket("@tcp://localhost:5556"))
     {
         var authResponse = server.ReceiveFrameString();
         server.SendFrame("Auth response received.");
         return(authResponse);
     }
 }
Exemple #29
0
        public void ConnectionStringWithWhiteSpace()
        {
            using (var response = new ResponseSocket(" >tcp://127.0.0.1:51503 "))
                using (var request = new RequestSocket("@tcp://127.0.0.1:51503, "))
                {
                    request.SendFrame("Hello");

                    Assert.AreEqual("Hello", response.ReceiveFrameString());
                }
        }
Exemple #30
0
        public void ConnectionStringSpecifyNonDefault()
        {
            using (var response = new ResponseSocket(">tcp://127.0.0.1:51502"))
                using (var request = new RequestSocket("@tcp://127.0.0.1:51502"))
                {
                    request.SendFrame("Hello");

                    Assert.AreEqual("Hello", response.ReceiveFrameString());
                }
        }
Exemple #31
0
        private static void Main()
        {
            Console.Title = "NetMQ HelloWorld";

            using (var server = new ResponseSocket("@tcp://localhost:5556"))
            using (var client = new RequestSocket("tcp://localhost:5556"))
            {
                client.SendFrame("Hello");

                Console.WriteLine("From Client: {0}", server.ReceiveFrameString());

                server.SendFrame("Hi Back");

                Console.WriteLine("From Server: {0}", client.ReceiveFrameString());

                Console.WriteLine();
                Console.Write("Press any key to exit...");
                Console.ReadKey();
            }
        }
Exemple #32
0
        private static void Main()
        {
            using (var response = new ResponseSocket())
            {
                string address = GetComputerLanIP();

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

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

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

                        Thread.Sleep(1000);
                    }

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

                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
Exemple #33
0
        private static void Main()
        {
            Console.Title = "NetMQ LazyPirate Server 2";

            const string serverEndpoint = "tcp://127.0.0.1:5555";

            var random = new Random();

            using (var server = new ResponseSocket())
            {
                Console.WriteLine("S: Binding address {0}", serverEndpoint);
                server.Bind(serverEndpoint);

                var cycles = 0;

                while (true)
                {
                    var request = server.ReceiveFrameString();
                    cycles++;

                    if (cycles > 3 && random.Next(0, 10) == 0)
                    {
                        Console.WriteLine("S: Simulating a crash");
                        Thread.Sleep(5000);
                    }
                    else if (cycles > 3 && random.Next(0, 10) == 0)
                    {
                        Console.WriteLine("S: Simulating CPU overload");
                        Thread.Sleep(1000);
                    }

                    Console.WriteLine("S: Normal request ({0})", request);
                    server.SendFrame(request);
                }
            }
        }