/// <summary> /// protocol for NetMq /// the <message> should be a string send as the second frame and the message must not contain more that two frames or it will be discarded by the server /// "A" as first frame if you want <message> + " hello" as response /// "B" as first frame if you want "hello " + <message> /// </summary> static void Main(string[] args) { Console.WriteLine("NetMQ server have started"); var server = new ResponseSocket(); server.Bind("tcp://*:" + ListeningPort); while (true) { var message = server.ReceiveMultipartMessage(); if (message.FrameCount == 2) { var frameOne = message[0]; Console.WriteLine("recived message with protocol code: " + frameOne.ConvertToString()); //sending response if (frameOne.ConvertToString() == "A") { server.SendFrame(message[1].ConvertToString() + " hello"); continue; } else if (frameOne.ConvertToString() == "B") { server.SendFrame(message[1].ConvertToString() + " hello"); continue; } } //must only occure if the message is not valid according to the protocol server.SendFrame("INVALID FRAME COUNT!"); } }
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; } } } }
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); } } } }
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"); }; } } }
void Respond() { AsyncIO.ForceDotNet.Force(); var socket = new ResponseSocket("tcp://*:5558"); try{ while (responderIsStarted) { string inMsg; if (!socket.TryReceiveFrameString(out inMsg)) { continue; } Debug.Log("Received: " + inMsg); if (inMsg == "on") { lightIsOn = true; socket.SendFrame("Light is on"); } else if (inMsg == "off") { lightIsOn = false; socket.SendFrame("Light is off"); } } }finally{ if (socket != null) { socket.Close(); ((IDisposable)socket).Dispose(); NetMQConfig.Cleanup(true); } } }
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"); } }
void ReplyInformation(Guid id, string name) { using (var responder = new ResponseSocket($"$tcp://{EndPoint.ToString()}")) { responder.SendFrame(id.ToString()); responder.SendFrame(name); } }
private void AccountRequest(int strategyId) { using (var context = new MyDBContext()) { Account account = context.Account.SingleOrDefault(x => x.StrategyID == strategyId); using (var ms = new MemoryStream()) { responseSocket.SendFrame(MyUtils.ProtoBufSerialize(account, ms)); } } }
// https://stackoverflow.com/questions/1156058/how-do-you-interrupt-a-socket-receivefrom-call private void startServer(IConsole con, ResponseSocket socket) { con.WriteLine("client must send [FIN] to stop."); // currently this is the only way! string request = ""; while ((request = socket.ReceiveFrameString()) != "[FIN]") { _animals.Add(request); con.WriteLine(request); socket.SendFrame($"(OK) {request}"); } socket.SendFrame($"(OK) [FIN]"); }
private void ResponseEntry() { using (ResponseSocket serverSocket = new ResponseSocket()) { string endpoint = "tcp://*:" + ModResponse.port; try { serverSocket.Bind(endpoint); } catch (Exception err) { Logging.logger.Error(ModName + " bind response socket failed " + endpoint + " " + err.Message); throw (err); } ResponseRM.ressock = serverSocket; string received = string.Empty; bool result; string resdata = string.Empty; ResponseRM.Working = true; while (ResponseRM.Running) { //string received = serverSocket.ReceiveFrameString(); received = string.Empty; result = serverSocket.TryReceiveFrameString(out received); if (result == true) { try { resdata = this.ResponseEntry(received); serverSocket.SendFrame(resdata); } catch (Exception err) { Logging.logger.Error(err.Message); resdata = Entry4ExceptionMsg(err.Message); serverSocket.SendFrame(resdata); throw (err); } } DelayTime(); } ResponseRM.Working = false; serverSocket.Close(); } }
public void ErrorCodeTest() { using (var req = new RequestSocket()) using (var rep = new ResponseSocket()) using (var monitor = new NetMQMonitor(req, "inproc://rep.inproc", SocketEvents.ConnectDelayed)) { var eventArrived = false; monitor.ConnectDelayed += (s, a) => { eventArrived = true; }; monitor.Timeout = TimeSpan.FromMilliseconds(100); var monitorTask = Task.Factory.StartNew(monitor.Start); var port = rep.BindRandomPort("tcp://127.0.0.1"); req.Connect("tcp://127.0.0.1:" + port); req.SendFrame("a"); rep.SkipFrame(); rep.SendFrame("b"); req.SkipFrame(); Thread.Sleep(200); Assert.IsTrue(eventArrived); monitor.Stop(); Thread.Sleep(200); Assert.IsTrue(monitorTask.IsCompleted); } }
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); } } }
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(); }
private void ListenerWork() { UnityEngine.Debug.Log("ListenerWork "); AsyncIO.ForceDotNet.Force(); using (var server = new ResponseSocket()) { server.Bind("tcp://*:12346"); while (!_listenerCancelled) { UnityEngine.Debug.Log("!ListenerCancelled"); Connected = _contactWatch.ElapsedMilliseconds < ContactThreshold; string message; if (!server.TryReceiveFrameString(out message)) { continue; } _contactWatch.Restart(); var response = _messageDelegate(message); server.SendFrame(response); //Thread.Sleep(thread_sleep_time); } } NetMQConfig.Cleanup(); }
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."); } } }
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); } }
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; } } }
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(); } }
public void RequestReply() { ThreadPool.QueueUserWorkItem(state => { var server = new ResponseSocket(); server.Bind("tcp://*:5555"); while (!_stopLoops) { try { var receiveFrame = server.ReceiveFrameBytes(); var request = Serializer.Deserialize <Request>(new MemoryStream(receiveFrame)); var response = OnRequest(request); using (var responseStream = new MemoryStream()) { Serializer.Serialize(responseStream, response); server.SendFrame(responseStream.ToArray()); } } catch (Exception e) { Console.WriteLine(e); } } }); }
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); } } }
private bool ProcessMessage(string msg) { Command cmd = Command.CreateCommand(msg); bool returnval = true; switch (cmd.Action) { case Command.ActionKind.Start: //Console.WriteLine("Start ProcessId: {0}", cmd.Parameters[Command.ParameterName.ProcessId.ToString()]); sub.AddListener(Int32.Parse(cmd.Parameters[Command.ParameterName.ProcessId.ToString()])); break; case Command.ActionKind.Log: //Console.WriteLine("Log AppName: {0} Message{1}", cmd.Parameters[Command.ParameterName.AppName.ToString()], cmd.Parameters[Command.ParameterName.Message.ToString()]); LogData(cmd); break; case Command.ActionKind.Stop: //Console.WriteLine("Stop ProcessId: {0}", cmd.Parameters[Command.ParameterName.ProcessId.ToString()]); sub.RemoveListener(Int32.Parse(cmd.Parameters[Command.ParameterName.ProcessId.ToString()])); if (!sub.IsListenerPresent()) { returnval = false; } break; } socket.SendFrame("Received"); return(returnval); }
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"); } } }
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); } }
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"); } } }
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 }
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); } }
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."); } }
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 "); } } }
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 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); }
private static void Main() { using (var worker = new ResponseSocket()) { worker.Connect(WorkerEndpoint); while (true) { var msg = worker.ReceiveMultipartMessage(); Console.WriteLine("Processing Message {0}", msg.Last.ConvertToString()); Thread.Sleep(500); worker.SendFrame(msg.Last.ConvertToString()); } } }
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(); } }
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(); } }
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); } } }