NetMQ使用——请求响应模式 Request-Reply
官网:https://netmq.readthedocs.io/en/latest/receiving-sending/
推荐:https://www.cnblogs.com/Jack-Blog/p/6774902.html
先发送的服务器端
using (NetMQSocket clientSocket = new RequestSocket()) { Random rd = new Random(); int num = rd.Next(0, 100); clientSocket.Connect("tcp://127.0.0.1:5555"); while (true) { Console.WriteLine(num + ",Please enter your message:"); string message = Console.ReadLine(); clientSocket.SendFrame(num + ":" + message); string answer = clientSocket.ReceiveFrameString(); Console.WriteLine("Answer from server:{0}", answer); if (message == "exit") { break; } } }
接收方,并返回接收结果
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 if (message == "ni hao ") { serverSocket.SendFrame("你好!"); } else if (message == "hi") { serverSocket.SendFrame("HI"); } else { serverSocket.SendFrame(message); } #endregion if (message == "exit") { break; } } }
上述的绑定方法是一一对应的,不能同时开启多个客户端,若想绑定多个客户端,则要改变绑定的方式
using (NetMQSocket clientSocket = new RequestSocket("@tcp://127.0.0.1:5555"))
using (NetMQSocket serverSocket = new ResponseSocket(">tcp://127.0.0.1:5555"))