static bool SendMsg(ZSocket sock, ZMessage msg, out ZError error) { error = ZError.None; foreach (ZFrame frame in msg) { while (-1 == zmq.msg_send(frame.Ptr, sock.SocketPtr, (int)(/* ZSocketFlags.DontWait | */ ZSocketFlags.More))) { error = ZError.GetLastErr(); if (error == ZError.EINTR) { error = default(ZError); continue; } /* if (error == ZError.EAGAIN) * { * error = default(ZError); * Thread.Sleep(1); * * continue; * } */ return(false); } } return(true); }
/// <summary> /// 响应 服务器端 /// </summary> /// <param name="port"></param> /// <param name="messageHandler">不能为null,否则抛出异常,MessageHandler不能抛出异常</param> public static void ReqServer(int port, Func <String, String> messageHandler) { //ZContext实例 using (ZContext context = new ZContext()) { //ZSocket实例 响应 using (ZSocket responder = new ZSocket(context, ZSocketType.REP)) { ZError zError = null; bool result = responder.Bind($"tcp://*:{port}", out zError); while (isRunning) { //接收消息 using (ZFrame request = responder.ReceiveFrame()) { //Response socket always reply to the last client that sends a message. String msg = request.ReadString(Encoding.UTF8); String resp = messageHandler(msg); responder.Send(new ZFrame(resp, Encoding.UTF8)); } } } } }
// The static constructor prepares static readonly fields static zmq() { // Set once LibVersion to libversion() int major, minor, patch; version(out major, out minor, out patch); LibraryVersion = new Version(major, minor, patch); // Trigger static constructor // TODO this is also done in the static initializer of ZError. Can this be unified? var noError = ZError.GetLastErr(); var noSym = ZSymbol.None; if (major >= 4) { // Current Version 4 // Use default delegate settings from field initializers. // "Compatibility" is done by "disabling" old methods, or "redirecting" to new methods, // so the developer is forced to work against the latest API if (minor == 0) { sizeof_zmq_msg_t = sizeof_zmq_msg_t_v3; } } else { throw VersionNotSupported(null, ">= v4"); } }
private void LogError(ZError error, string context) { // TODO: this error handling is somewhat too subtle; the client should be able to retrieve it if (error != ZError.ETERM) { Trace.TraceError("error on {0}: {1}", context, error.ToString()); } }
private bool SubscriberHandler(ZSocket socket, out ZMessage message, out ZError error) { message = socket.ReceiveMessage(); String payload = message[1].ReadString(); this.event_socket.Send(new ZFrame(payload)); error = default(ZError); return(true); }
private bool AsyncHandler(ZSocket socket, out ZMessage message, out ZError error) { message = socket.ReceiveMessage(); String payload = message[0].ReadString(); socket.Send(new ZFrame(socket.IdentityString)); // do something with payload excel.ActiveSheet.Cells[1, 1] = "FUUUUUCK!"; error = null; return(true); }
/// <summary> /// Create a socket with the current context and the specified socket type. /// </summary> /// <param name="socketType">A <see cref="ZSocketType"/> value for the socket.</param> /// <returns>A <see cref="ZSocket"/> instance with the current context and the specified socket type.</returns> public static ZMonitor Create(ZContext context, string endpoint, out ZError error) { ZSocket socket; if (null == (socket = ZSocket.Create(context, ZSocketType.PAIR, out error))) { return(default(ZMonitor)); } return(new ZMonitor(context, socket, endpoint)); }
public static void ErrorChecker(ZError error) { if (error == ZError.ETERM) { return; // Interrupted } if (error != ZError.EAGAIN) { throw new ZException(error); } }
public static void SendMsg(ZSocket socket, string msg) { ZError error = null; socket.SendFrame(new ZFrame("OOOO:" + msg), ZSocketFlags.DontWait, out error); using (var reply = socket.ReceiveFrame(ZSocketFlags.DontWait, out error)) { Console.WriteLine("Client::get reply:" + reply?.ReadString()); Thread.Sleep(new Random().Next(500, 900)); } }
/// <summary> /// 发送一次数据 /// </summary> /// <param name="socket"></param> /// <param name="str"></param> /// <param name="error"></param> /// <returns></returns> public static bool SendOnce(this ZSocket socket, string str, out ZError error) { if (socket == null) { throw new System.ArgumentNullException(typeof(ZSocket).Name); } error = null; using (var frame = new ZFrame(str, System.Text.Encoding.UTF8)) { return(socket.SendFrame(frame, out error)); } }
public void Stop(ZError error = null) { _serverToWorkerSocket?.Dispose(); if (error == null || error == ZError.ETERM) { // ignore it return; } throw new ZException(error); }
ZSocket CreateSocket(out ZError error) { var socket = new ZSocket(NetMqManager.Instance.Context, ZSocketType.REQ); socket.Connect(ReqAddress); socket.IdentityString = BaseNetMqServer.GenerateKey("CLIENT"); socket.Linger = TimeSpan.FromMilliseconds(1); if (!socket.Connect(ReqAddress, out error)) { return(null); } return(socket); }
static bool ReceiveMsg(ZSocket sock, ref ZMessage message, out string address, out ZError error) { error = ZError.None; // address = IPAddress.None; address = string.Empty; // STREAM: read frames: identity, body // read the ip4 address from (ZFrame)frame.GetOption("Peer-Address") int receiveCount = 2; do { var frame = ZFrame.CreateEmpty(); while (-1 == zmq.msg_recv(frame.Ptr, sock.SocketPtr, (int)(/* ZSocketFlags.DontWait | */ ZSocketFlags.More))) { error = ZError.GetLastErr(); if (error == ZError.EINTR) { error = default(ZError); continue; } frame.Close(); return(false); } if (message == null) { message = new ZMessage(); } message.Add(frame); if (receiveCount == 2) { if (default(string) == (address = frame.GetOption("Peer-Address", out error))) { // just ignore error = default(ZError); address = string.Empty; } } } while (--receiveCount > 0); return(true); }
static ZSocket LPClient_CreateZSocket(ZContext context, string name, out ZError error) { // Helper function that returns a new configured socket // connected to the Lazy Pirate queue var requester = ZSocket.Create(context, ZSocketType.REQ); requester.IdentityString = name; if (!requester.Connect("tcp://127.0.0.1:5555", out error)) { return(null); } return(requester); }
// // Lazy Pirate client // Use zmq_poll (pollItem.PollIn) to do a safe request-reply // To run, start lpserver and then randomly kill/restart it // // Author: metadings // public ZSocket LPClient_CreateZSocket(ZContext context, out ZError error) { // Helper function that returns a new configured socket // connected to the Lazy Pirate queue var requester = new ZSocket(context, ZSocketType.REQ); requester.IdentityString = name; requester.Linger = TimeSpan.FromMilliseconds(1); if (!requester.Connect("tcp://localhost:" + port, out error)) { return(null); } return(requester); }
public static void ReceiveOnece(ZSocket socket) { ZError error = null; using (var frame = socket.ReceiveFrame(out error)) { if (error != null) { throw new Exception(error.Text); } Console.WriteLine("Server::Get-request::{0}", frame.ReadString()); Thread.Sleep(new Random().Next(100, 300)); var msg = new Random().Next(1000, 9999).ToString(); socket.SendFrame(new ZFrame("NONO::" + msg)); } }
/// <summary> /// Forwards requests from the frontend socket to the backend socket. /// </summary> protected override bool FrontendHandler(ZSocket sock, out ZMessage message, out ZError error) { error = default(ZError); message = null; // receiving scope // STREAM: get 2 frames, identity and body ZMessage incoming = null; // IPAddress address = null; string address; if (!ReceiveMsg(sock, ref incoming, out address, out error)) { return(false); } // sending scope // DEALER: forward using (incoming) { if (incoming[1].Length == 0) { return(true); // Ignore the Empty one } // Prepend empty delimiter between Identity frame and Data frame incoming.Insert(1, new ZFrame()); // Prepend Peer-Address incoming.Insert(2, new ZFrame(address)); try { if (!BackendSocket.Send(incoming, /* ZSocketFlags.DontWait, */ out error)) { return(false); } } finally { incoming.Dismiss(); } } return(true); }
static ZSocket LPClient_CreateZSocket(ZContext context, string name, out ZError error) { // Helper function that returns a new configured socket // connected to the Lazy Pirate queue var requester = new ZSocket(context, ZSocketType.REQ); requester.IdentityString = name; // The linger period determines how long pending messages which have yet to be sent to a peer shall linger in memory after a socket is closed //Set linger period for socket shutdown requester.Linger = TimeSpan.FromMilliseconds(1); if (!requester.Connect("tcp://127.0.0.1:5555", out error)) { return(null); } return(requester); }
public void PollInSingle_CancelByContextClose() { Task task; ZError error = null; using (var context = new ZContext()) { var socket = new ZSocket(context, ZSocketType.PAIR); task = Task.Run(() => { using (socket) { ZMessage message; socket.PollIn(ZPollItem.CreateReceiver(), out message, out error); } }); } Assert.IsTrue(task.Wait(1000)); Assert.AreEqual(ZError.ETERM, error); }
/// <summary> /// 接收一次数据 /// </summary> /// <param name="socket"></param> /// <param name="error"></param> /// <returns></returns> public static string RecvOnce(this ZSocket socket, out ZError error) { if (socket == null) { throw new System.ArgumentNullException(typeof(ZSocket).Name); } error = null; using (var frame = socket.ReceiveFrame(ZSocketFlags.None, out error)) { if (error != null) { return(null); } if (frame != null) { var str = frame.ReadString(); return(str); } } return(null); }
/// <summary> /// Forwards replies from the backend socket to the frontend socket. /// </summary> protected override bool BackendHandler(ZSocket sock, out ZMessage message, out ZError error) { error = default(ZError); message = null; // receiving scope // DEALER: normal movemsg ZMessage incoming = null; if (!sock.ReceiveMessage(ref incoming, /* ZSocketFlags.DontWait */ ZSocketFlags.None, out error)) { return(false); } using (incoming) { // STREAM: write frames: identity, body, identity, empty // Read identity int ic = (int)incoming[0].Length; var identityBytes = new byte[ic]; incoming[0].Read(identityBytes, 0, ic); // Remove DEALER's delimiter incoming.RemoveAt(1); // Append Identity frame var identity0 = new ZFrame(identityBytes); incoming.Add(identity0); // Append STREAM's empty delimiter frame incoming.Add(new ZFrame()); if (!SendMsg(FrontendSocket, incoming, out error)) { return(false); } } return(true); }
/// <summary> /// Forwards requests from the frontend socket to the backend socket. /// </summary> protected override bool FrontendHandler(ZSocket sock, out ZMessage message, out ZError error) { error = default(ZError); message = null; // receiving scope // STREAM: get 2 frames, identity and body ZMessage incoming = null; // IPAddress address = null; string address; if (!ReceiveMsg(sock, ref incoming, out address, out error)) { return false; } // sending scope // DEALER: forward using (incoming) { if (incoming[1].Length == 0) { return true; // Ignore the Empty one } // Prepend empty delimiter between Identity frame and Data frame incoming.Insert(1, new ZFrame()); // Prepend Peer-Address incoming.Insert(2, new ZFrame(address)); if (!BackendSocket.Send(incoming, /* ZSocketFlags.DontWait, */ out error)) { return false; } incoming.Dismiss(); } return true; }
/// <summary> /// Forwards replies from the backend socket to the frontend socket. /// </summary> protected override bool BackendHandler(ZSocket sock, out ZMessage message, out ZError error) { error = default(ZError); message = null; // receiving scope // DEALER: normal movemsg ZMessage incoming = null; if (!sock.ReceiveMessage(ref incoming, /* ZSocketFlags.DontWait */ ZSocketFlags.None, out error)) { return false; } using (incoming) { // STREAM: write frames: identity, body, identity, empty // Read identity int ic = (int)incoming[0].Length; var identityBytes = new byte[ic]; incoming[0].Read(identityBytes, 0, ic); // Remove DEALER's delimiter incoming.RemoveAt(1); // Append Identity frame var identity0 = new ZFrame(identityBytes); incoming.Add(identity0); // Append STREAM's empty delimiter frame incoming.Add(new ZFrame()); if (!SendMsg(FrontendSocket, incoming, out error)) { return false; } } return true; }
static ZSocket PPWorker_CreateZSocket(ZContext context, string name, out ZError error) { // Helper function that returns a new configured socket // connected to the Paranoid Pirate queue var worker = new ZSocket(context, ZSocketType.DEALER); worker.IdentityString = name; if (!worker.Connect("tcp://127.0.0.1:5556", out error)) { return(null); // Interrupted } // Tell queue we're ready for work using (var outgoing = new ZFrame(Worker.PPP_READY)) { worker.Send(outgoing); } Console.WriteLine("I: worker ready"); return(worker); }
public void PollInMany_CancelByContextClose() { Task task; ZError error = null; using (var context = new ZContext()) { var socket = new ZSocket(context, ZSocketType.PAIR); task = Task.Run(() => { using (socket) { var sockets = new[] { socket }; var pollItems = new[] { ZPollItem.CreateReceiver() }; ZMessage[] messages; sockets.PollIn(pollItems, out messages, out error, TimeSpan.Zero); } }); } Assert.IsTrue(task.Wait(1000)); Assert.AreEqual(ZError.ETERM, error); }
/// <summary> /// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for /// the specified socket over the inproc transport at the given endpoint. /// </summary> public static bool Monitor(this ZSocket socket, string endpoint, ZMonitorEvents eventsToMonitor, out ZError error) { if (socket == null) { throw new ArgumentNullException("socket"); } if (endpoint == null) { throw new ArgumentNullException("endpoint"); } if (endpoint == string.Empty) { throw new ArgumentException("Unable to publish socket events to an empty endpoint.", "endpoint"); } error = ZError.None; using (var endpointPtr = DispoIntPtr.AllocString(endpoint)) { while (-1 == zmq.socket_monitor(socket.SocketPtr, endpointPtr, (Int32)eventsToMonitor)) { error = ZError.GetLastErr(); if (error == ZError.EINTR) { error = default(ZError); continue; } return false; } } return true; }
/// <summary> /// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for /// the specified socket over the inproc transport at the given endpoint. /// </summary> public static bool Monitor(this ZSocket socket, string endpoint, ZMonitorEvents eventsToMonitor, out ZError error) { if (socket == null) { throw new ArgumentNullException("socket"); } if (endpoint == null) { throw new ArgumentNullException("endpoint"); } if (endpoint == string.Empty) { throw new ArgumentException("Unable to publish socket events to an empty endpoint.", "endpoint"); } error = ZError.None; using (var endpointPtr = DispoIntPtr.AllocString(endpoint)) { while (-1 == zmq.socket_monitor(socket.SocketPtr, endpointPtr, (Int32)eventsToMonitor)) { error = ZError.GetLastErr(); if (error == ZError.EINTR) { error = default(ZError); continue; } return(false); } } return(true); }
public static bool DefaultSendMessage(ZSocket socket, ZMessage message, out ZError error) { return(socket.Send(message, out error)); }
/// <summary> /// Forwards replies from the backend socket to the frontend socket. /// </summary> protected override bool BackendHandler(ZSocket args, out ZMessage message, out ZError error) { return(BackendSocket.Forward(FrontendSocket, out message, out error)); }
/// <summary> /// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for /// the specified socket over the inproc transport at the given endpoint. /// </summary> public static bool Monitor(this ZSocket socket, string endpoint, out ZError error) { return Monitor(socket, endpoint, ZMonitorEvents.AllEvents, out error); }
public static bool DefaultReceiveMessage(ZSocket socket, out ZMessage message, out ZError error) { message = null; return(socket.ReceiveMessage(ref message, out error)); }
void _RecvRoute(object obj) { using (var ctx = new ZContext()) using (var skt = new ZSocket(ctx, ZSocketType.SUB)) { skt.SubscribeAll(); //skt. //skt.SetOption(ZSocketOption.IDENTITY, "yoyotek.cn"); //skt.SetOption(ZSocketOption.RCVHWM, 0); //skt.Subscribe("BDPK"); // WDPK, 五档盘口 // SDPK, 十档盘口 // ZBCJ,逐笔成交 // ZBWT,逐笔委托 // ZBDD,逐笔大单 // BDPK,百档盘口 // QQPK,期权盘口 skt.ReceiveHighWatermark = 0; skt.MulticastRate = 10000; skt.Connect(ConfigurationManager.AppSettings["ZMQServer"]); while (true) { try { //var bytes = _udpClient.Receive(ref _ipEndPoint); ZError zerr = new ZError(0); //skt.SetOption(ZSocketOption.SUBSCRIBE, ""); var frms = skt.ReceiveFrames(100); frms.ToList().AsParallel().ForAll(frm => { var bytes = frm.Read(); //var str = frm. //if (string.IsNullOrEmpty(str) || str == "UNKNOWN") //{ // return null; //} //else //{ // var dit = new Dictionary<string, string>(); // str.Split(new char[] { ';' }).ToList().ForEach(kv => // { // var pair = kv.Split(new char[] { '=' }); // if (pair.Length == 2) // dit.Add(pair[0], pair[1]); // }); // return dit; //} //writelog("dzh_recvthread.log", "thread is:" + Thread.CurrentThread.ManagedThreadId.ToString() + " received!"); _ResolveDatagram(bytes); frm.Close(); if (_hsAltered.Any() && QuoteChanged != null) { QuoteChanged(); } }); } catch (ThreadAbortException) { //LogManager.LogMgr.WriteLog(LogManager.LogFile.Trace, "UDP recv aborted."); } catch (System.Exception ex) { //LogManager.LogMgr.WriteLog(LogManager.LogFile.Error, "UDP recv err:" + ex.Message); writelog(DateTime.Now.ToString("yyyyMMdd") + "\\exception.txt", ex.Message); } } } }
/// <summary> /// 中间路由分发器 /// </summary> /// <param name="routerPort">路由绑定端口</param> /// <param name="dealerPort">分发绑定端口</param> public static void RouterDealer(int routerPort, int dealerPort) { using (var router = new ZSocket(zContext, ZSocketType.ROUTER)) { using (var dealer = new ZSocket(zContext, ZSocketType.DEALER)) { router.Bind($"tcp://*:{routerPort}"); dealer.Bind($"tcp://*:{dealerPort}"); //初始化 Poll set ZPollItem poll = ZPollItem.CreateReceiver(); //路由 //switch messages between sockets ZError error = null; ZMessage message = null; DateTime lastErrorTime = DateTime.Now.AddDays(-1); int logIntervalSeconds = 19; long errorCount = 0;//错误次数 while (isRunning) { if (router.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(32))) { //转发消息 dealer.Send(message); } else { #region 处理错误 if (error != null && error.Number != ZError.EAGAIN.Number) { //Eagain表示重试 //记录日志 errorCount++; if (errorCount > 1000000) { errorCount = 1; } if (errorCount % 10 == 0) { Thread.Sleep(10); } if ((DateTime.Now - lastErrorTime).TotalSeconds > logIntervalSeconds) { lastErrorTime = DateTime.Now; NLogHelper.Error($"Router接收消息失败,错误码={error}"); } } #endregion } if (dealer.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(32))) { router.Send(message); } else { #region 处理错误 if (error != null && error.Number != ZError.EAGAIN.Number) { //Eagain表示重试 //记录日志 errorCount++; if (errorCount > 1000000) { errorCount = 1; } if (errorCount % 10 == 0) { Thread.Sleep(10); } if ((DateTime.Now - lastErrorTime).TotalSeconds > logIntervalSeconds) { lastErrorTime = DateTime.Now; NLogHelper.Error($"Router接收消息失败,错误码={error}"); } } #endregion } } } } }
/// <summary> /// PubSub Forwards the Subscription messages /// </summary> protected override bool BackendHandler(ZSocket args, out ZMessage message, out ZError error) { return BackendSocket.Forward(FrontendSocket, out message, out error); }
/// <summary> /// Create a socket with the current context and the specified socket type. /// </summary> /// <param name="socketType">A <see cref="ZSocketType"/> value for the socket.</param> /// <returns>A <see cref="ZSocket"/> instance with the current context and the specified socket type.</returns> public static ZMonitor Create(string endpoint, out ZError error) { return(Create(ZContext.Current, endpoint, out error)); }
static bool ReceiveMsg(ZSocket sock, ref ZMessage message, out string address, out ZError error) { error = ZError.None; // address = IPAddress.None; address = string.Empty; // STREAM: read frames: identity, body // read the ip4 address from (ZFrame)frame.GetOption("Peer-Address") int receiveCount = 2; do { var frame = ZFrame.CreateEmpty(); while (-1 == zmq.msg_recv(frame.Ptr, sock.SocketPtr, (int)(/* ZSocketFlags.DontWait | */ ZSocketFlags.More))) { error = ZError.GetLastErr(); if (error == ZError.EINTR) { error = default(ZError); continue; } frame.Dispose(); return false; } if (message == null) { message = new ZMessage(); } message.Add(frame); if (receiveCount == 2) { if (default(string) == (address = frame.GetOption("Peer-Address", out error))) { // just ignore error = default(ZError); address = string.Empty; } } } while (--receiveCount > 0); return true; }
static bool SendMsg(ZSocket sock, ZMessage msg, out ZError error) { error = ZError.None; try { foreach (ZFrame frame in msg) { while (-1 == zmq.msg_send(frame.Ptr, sock.SocketPtr, (int)(/* ZSocketFlags.DontWait | */ ZSocketFlags.More))) { error = ZError.GetLastErr(); if (error == ZError.EINTR) { error = default(ZError); continue; } /* if (error == ZError.EAGAIN) { error = default(ZError); Thread.Sleep(1); continue; } */ return false; } } } finally { msg.Dismiss(); } return true; }
/// <summary> /// Not implemented for the <see cref="StreamerDevice"/>. /// </summary> protected override bool BackendHandler(ZSocket args, out ZMessage message, out ZError error) { throw new NotSupportedException(); }