private static ZmqSocket GetConnectedPublishSocket(ZmqContext context) { ZmqSocket publisher = context.CreateSocket(SocketType.PUB); publisher.Connect("tcp://localhost:5556"); return(publisher); }
public void ConnectFor(TransportMessage message) { if (!CanSendOrConnect(message)) { return; } try { _socket = new ZmqSocket(_context, ZmqSocketType.PUSH); _socket.SetOption(ZmqSocketOption.SNDHWM, _options.SendHighWaterMark); _socket.SetOption(ZmqSocketOption.SNDTIMEO, (int)_options.SendTimeout.TotalMilliseconds); _socket.SetOption(ZmqSocketOption.TCP_KEEPALIVE, 1); _socket.SetOption(ZmqSocketOption.TCP_KEEPALIVE_IDLE, 30); _socket.SetOption(ZmqSocketOption.TCP_KEEPALIVE_INTVL, 3); _socket.SetOption(ZmqSocketOption.ROUTING_ID, Encoding.ASCII.GetBytes(PeerId.ToString())); _socket.Connect(EndPoint); IsConnected = true; _logger.InfoFormat("Socket connected, Peer: {0}, EndPoint: {1}", PeerId, EndPoint); } catch (Exception ex) { _socket.Dispose(); _socket = null; IsConnected = false; _logger.ErrorFormat("Unable to connect socket, Peer: {0}, EndPoint: {1}, Exception: {2}", PeerId, EndPoint, ex); _errorHandler.OnConnectException(PeerId, EndPoint, ex); SwitchToClosedState(_options.ClosedStateDurationAfterConnectFailure); } }
/// <summary> /// Initializes a new instance of the <see cref="ZmqResponseQueue"/> class. /// </summary> /// <param name="context">The context.</param> /// <param name="port">The port.</param> internal ZmqResponseQueue(ZmqContext context, int port) { socket = context.CreateSocket(SocketType.REP); var address = string.Format("tcp://127.0.0.1:{0}", port); socket.Bind(address); }
private static void WorkerTaskB() { using (var context = ZmqContext.Create()) { using (ZmqSocket worker = context.CreateSocket(SocketType.DEALER)) { worker.Identity = Encoding.Unicode.GetBytes("B"); worker.Connect("tcp://localhost:5555"); int total = 0; bool end = false; while (!end) { string request = worker.Receive(Encoding.Unicode); if (request.Equals("END")) { end = true; } else { total++; } } Console.WriteLine("B Received: {0}", total); } } }
public static void Main(string[] args) { using (var context = ZmqContext.Create()) { using (ZmqSocket subscriber = context.CreateSocket(SocketType.SUB), syncClient = context.CreateSocket(SocketType.REQ)) { subscriber.Connect("tcp://localhost:5561"); subscriber.Subscribe(Encoding.Unicode.GetBytes(string.Empty)); syncClient.Connect("tcp://localhost:5562"); // - send a synchronization request syncClient.Send("", Encoding.Unicode); // - wait for synchronization reply syncClient.Receive(Encoding.Unicode); int receivedUpdates = 0; while (!subscriber.Receive(Encoding.Unicode).Equals("END")) { receivedUpdates++; } Console.WriteLine("Received {0} updates.", receivedUpdates); } } Console.ReadKey(); }
public void InProcOnlyWithForwarder() { string expectedAddress = "XXXX"; string message = "hello its me"; int count = 0; using (var context = ZmqContext.Create()) { Pipe pipe = new Pipe(); pipe.Start(context); Task.Run(() => { return(RunSubscriber(context)); }); using (ZmqSocket pub = Helper.GetConnectedPublishSocket(context, Pipe.PublishAddressClient), syncService = context.CreateSocket(SocketType.REP)) { syncService.Connect(Pipe.PubSubControlFrontAddressClient); for (int i = 0; i < 1; i++) { syncService.Receive(Encoding.Unicode); syncService.Send("", Encoding.Unicode); } Helper.SendOneSimpleMessage(expectedAddress, message, pub); } pipe.Exit(); } }
public void InitialiseSocket() { m_PublishSocket = m_Context.CreateSocket(SocketType.PUB); m_PublishSocket.Bind("epgm://239.1.1.1:9500"); m_PublishSocket.Bind("tcp://*:9500"); m_PublishSocket.Bind("inproc://Local"); }
public void ConnectFor(TransportMessage message) { if (!CanSendOrConnect(message)) { return; } try { _socket = _context.CreateSocket(SocketType.PUSH); _socket.SendHighWatermark = _options.SendHighWaterMark; _socket.TcpKeepalive = TcpKeepaliveBehaviour.Enable; _socket.TcpKeepaliveIdle = 30; _socket.TcpKeepaliveIntvl = 3; _socket.SetPeerId(PeerId); _socket.Connect(EndPoint); IsConnected = true; _logger.InfoFormat("Socket connected, Peer: {0}, EndPoint: {1}", PeerId, EndPoint); } catch (Exception ex) { _socket.Dispose(); _socket = null; IsConnected = false; _logger.ErrorFormat("Unable to connect socket, Peer: {0}, EndPoint: {1}, Exception: {2}", PeerId, EndPoint, ex); _errorHandler.OnConnectException(PeerId, EndPoint, ex); SwitchToClosedState(_options.ClosedStateDurationAfterConnectFailure); } }
public Publisher(string _guid, string _host, int _port, ZmqContext _ctx) { guid = _guid; host = _host; port = _port; if (_ctx == null) { ctx = ZmqContext.Create(); } else { ctx = _ctx; } socket = ctx.CreateSocket(SocketType.PUB); var bindString = String.Empty; if (port > 0) { bindString = String.Format("tcp://*:{0}", port); } else { bindString = String.Format("inproc://{0}", guid.ToLower()); } socket.Bind(bindString); log.InfoFormat("Publisher successfuly binded on {0}", bindString); socket.SendHighWatermark = 1000000; socket.SendBufferSize = 128 * 1024; }
public void Start() { if (_reqSocket != null) { return; } _reqSocket = _context.CreateSocket(SocketType.DEALER); _reqSocket.Identity = BitConverter.GetBytes(_localPort); bool isConnected = false; while (!isConnected) { try { _reqSocket.Connect(_inprocHost); isConnected = true; } catch { Thread.Sleep(500); } } }
public static T ReceiveMessageofType <T>(ZmqSocket sub) { string address = string.Empty; ZmqMessage message = null; return(ReceiveMessage <T>(sub, out message, out address)); }
//public void SendOneMessageOfType<T>(string Address, T message, ISerializer serializer, ZmqSocket publisher) //{ // ZmqMessage zmqMessage = new ZmqMessage(); // zmqMessage.Append(new Frame(Encoding.Unicode.GetBytes(Address))); // zmqMessage.Append(new Frame(serializer.GetBuffer(message))); // publisher.SendMessage(zmqMessage); //} public static T ReceiveMessage <T>(ZmqSocket Subscriber, out ZmqMessage zmqMessage, out string address) { T result = default(T); ZmqMessage zmqOut = new ZmqMessage(); bool hasMore = true; string message = ""; address = string.Empty; int i = 0; while (hasMore) { Frame frame = Subscriber.ReceiveFrame(); if (i == 0) { address = Encoding.Unicode.GetString(frame.Buffer); } if (i == 1) { result = (T)JsonConvert.DeserializeObject <T>(Encoding.Unicode.GetString(frame.Buffer)); } i++; zmqOut.Append(new Frame(Encoding.Unicode.GetBytes(message))); hasMore = Subscriber.ReceiveMore; } zmqMessage = zmqOut; return(result); }
public static void Main(string[] args) { using (var context = ZmqContext.Create()) { using (ZmqSocket replyer = context.CreateSocket(SocketType.REP)) { replyer.Bind("tcp://*:5555"); bool interrupted = false; Console.CancelKeyPress += delegate { interrupted = true; }; const string replyMessage = "World"; while (!interrupted) { string message = replyer.Receive(Encoding.Unicode); Console.WriteLine("Received request: {0}", message); // Simulate work, by sleeping Thread.Sleep(1000); // Send reply back to client replyer.Send(replyMessage, Encoding.Unicode); } } } }
private static void WorkerTask() { using (var context = ZmqContext.Create()) { using (ZmqSocket worker = context.CreateSocket(SocketType.REQ)) { ZHelpers.SetID(worker, Encoding.Unicode); worker.Connect("tcp://localhost:5556"); // Tell broker we're ready for work worker.Send("READY", Encoding.Unicode); while (true) { // Read and save all frames until we get an empty frame // In this example there is only 1 but it could be more string address = worker.Receive(Encoding.Unicode); string empty = worker.Receive(Encoding.Unicode); // Get request, send reply string request = worker.Receive(Encoding.Unicode); Console.WriteLine("Worker: {0}", request); worker.SendMore(address, Encoding.Unicode); //worker.SendMore(); worker.Send("OK", Encoding.Unicode); } } } }
public ZmqPublisher(string endpoint) { _endpoint = endpoint; _context = ZmqContext.Create(); _socket = _context.CreateSocket(SocketType.PUB); _socket.Bind(_endpoint); }
public static void SendMessage(byte[] address, byte[] message, ZmqSocket socket) { ZmqMessage zmqMessage = new ZmqMessage(); zmqMessage.Append(new Frame(address)); zmqMessage.Append(new Frame(message)); socket.SendMessage(zmqMessage); }
static void Main(string[] args) { using (ZmqContext context = ZmqContext.Create()) using (ZmqSocket server = context.CreateSocket(SocketType.SUB)) { server.SubscribeAll(); for (int i = 1; i < 255; i++) { string address = string.Format("tcp://192.168.11.{0}:9000", i); try { server.Connect(address); } catch { } } while (true) { // Wait for next request from client string message = server.Receive(Encoding.ASCII); Console.WriteLine("{0}: {1}", DateTime.Now.ToShortTimeString(), message); } } }
public Subscriber(string _guid, string _targetGuid, string _host, int _port, ZmqContext _ctx) { guid = _guid; targetGuid = _targetGuid; host = _host; port = _port; if (port > 0) connectionString = String.Format("tcp://{0}:{1}", host, port); else connectionString = String.Format("inproc://{0}", targetGuid.ToLower()); buf = new byte[1024 * 1024]; subscribeChannels = new List<string>(); if (_ctx == null) { shardedCtx = false; ctx = ZmqContext.Create(); } else { shardedCtx = true; ctx = _ctx; } socket = ctx.CreateSocket(SocketType.SUB); if (log.IsDebugEnabled) log.DebugFormat("Subscriber connecting to: `{0}`", connectionString); socket.Subscribe(Proxy.StringToByteArray(guid)); socket.Connect(connectionString); socket.ReceiveHighWatermark = 1000000; socket.ReceiveBufferSize = 128 * 1024; lastActiveTime = Proxy.Unixtimestamp(); log.InfoFormat("Connected successfuly to: `{0}` `{1}`", connectionString, targetGuid); }
protected virtual ZmqSocket CreateSocket(string endPoint) { ZmqSocket receiver = ZeroMessageQueue.ZmqContext.CreateSocket(SocketType.PULL); receiver.Bind(endPoint); return(receiver); }
static void Main(string[] args) { // Prepare our context using (ZmqContext context = ZmqContext.Create()) { // Sockets to send and receive messages on using (ZmqSocket receiver = context.CreateSocket(SocketType.PULL), sender = context.CreateSocket(SocketType.PUSH)) { receiver.Connect("tcp://localhost:5557"); sender.Connect("tcp://localhost:5558"); // Process tasks forever while (true) { string message = receiver.Receive(Encoding.Unicode); // Simple progress indicator for the viewer Console.Clear(); Console.WriteLine("{0}.", message); // Do the work Thread.Sleep(Convert.ToInt32(message)); // Send results to sink sender.Send("", Encoding.Unicode); } } } }
public static void Main(string[] args) { using (var context = ZmqContext.Create()) { // Connect to task ventilator and weather server using (ZmqSocket receiver = context.CreateSocket(SocketType.PULL), subscriber = context.CreateSocket(SocketType.SUB)) { receiver.Connect("tcp://localhost:5557"); subscriber.Connect("tcp://localhost:5556"); subscriber.Subscribe(Encoding.Unicode.GetBytes("10001 ")); receiver.ReceiveReady += ReceiverPollInHandler; subscriber.ReceiveReady += SubscriberPollInHandler; var poller = new Poller(new List <ZmqSocket> { }); // Process messages from both sockets while (true) { poller.Poll(); } } } }
public static void Main(string[] args) { using (var context = ZmqContext.Create()) { using (ZmqSocket publisher = context.CreateSocket(SocketType.PUB)) { // your first potential issue lies here, if you're not // populating your addresses properly then you're not going to // bind appropriately // Test by hard coding the address publisher.Bind("tcp://127.0.0.1:5000"); int msgIndex = 0; while (true) { // your second potential issue lies here, if your logic // short circuits your send, that'll throw a wrench in the // works // Test by removing the logic and just sending a bunch of // messages var msg = "Message: " + msgIndex; // simplify Console.WriteLine("Publishing: " + msg); socket.Send(msg, Encoding.UTF8); Thread.Sleep(500); // hard code msgIndex++; if (msgIndex > 1500) { break; // hard code the break } } } } }
public static void SendRequest(Int32 request,ref ZmqSocket socket) { //ZmqSocket socket; try { //socket = CreateSocket(); var message = new ZmqMessage(); message.Append(Encoding.UTF8.GetBytes(String.Format(" Hello {0}.", request))); socket.SendMessage(message); // TODO: add receive timeout as param var dataResult = socket.ReceiveMessage(); Console.WriteLine(Encoding.UTF8.GetString(dataResult[0])); Console.WriteLine(Encoding.UTF8.GetString(dataResult[1])); } catch (Exception ex) { socket.Close(); socket = CreateSocket(); Console.WriteLine(ex.ToString()); } }
private static void Open(Object cancelationToken) { context = ZmqContext.Create(); frontend = context.CreateSocket(SocketType.ROUTER); backend = context.CreateSocket(SocketType.DEALER); backend.Identity = Encoding.UTF8.GetBytes("inproc://workers"); frontend.Bind("tcp://127.0.0.1:5000"); backend.Bind("inproc://workers"); workerThreads = new Thread[2]; for (int threadId = 0; threadId < workerThreads.Length; threadId++) { workerThreads[threadId] = new Thread(WorkerRoutine); workerThreads[threadId].Start(context); } frontend.ReceiveReady += new EventHandler<SocketEventArgs>(frontend_ReceiveReady); backend.ReceiveReady += new EventHandler<SocketEventArgs>(backend_ReceiveReady); Poller poller = new Poller(new[] { frontend, backend }); var token = (CancellationToken)cancelationToken; while (!token.IsCancellationRequested) { poller.Poll(TimeSpan.FromMilliseconds(100)); } }
private void RecieverPollInHandler(ZmqSocket reciever, ZmqSocket sender) { Thread.Sleep(100); var fileToMeasure = reciever.Receive(Encoding.Unicode); Int64 fileLength = 0; FileStream fs = null; try { fs = File.OpenRead(fileToMeasure); fileLength = fs.Length; } catch (IOException) { } finally { if (fs != null) fs.Dispose(); } Console.Write("."); sender.Send(fileLength.ToString(), Encoding.Unicode); }
public static void Main(string[] args) { using (var context = ZmqContext.Create()) { using (ZmqSocket receiver = context.CreateSocket(SocketType.PULL), sender = context.CreateSocket(SocketType.PUSH)) { receiver.Connect("tcp://localhost:5557"); sender.Connect("tcp://localhost:5558"); while (true) { string task = receiver.Receive(Encoding.Unicode); // Simple progress indicator for the viewer; Console.WriteLine("{0}.", task); int sleepTime = Convert.ToInt32(task); Thread.Sleep(sleepTime); // Send 'result' to the sink sender.Send("", Encoding.Unicode); } } } }
internal ZmqMessageSender(Uri serviceUri) { context = ZmqContext.Create(); socket = context.CreateSocket(SocketType.REQ); var address = string.Format("tcp://{0}:{1}", serviceUri.Host, serviceUri.Port); socket.Connect(address); }
public ClientForm() { InitializeComponent(); context = ZmqContext.Create(); client = context.CreateSocket(SocketType.REQ); client.Connect("tcp://localhost:5555"); }
private static string Sender(string input) { using (var context = ZmqContext.Create()) { using (ZmqSocket pub = Helper.GetConnectedPublishSocket(context, Pipe.PublishAddressClient), syncService = context.CreateSocket(SocketType.REP)) { //syncService.Connect(Pipe.PubSubControlFrontAddressClient); //for (int i = 0; i < 1; i++) //{ // syncService.Receive(Encoding.Unicode); // syncService.Send("", Encoding.Unicode); //} for (int i = 0; i < 100000; i++) { Console.WriteLine("Enter to send message=>"); input = Console.ReadLine(); SendMessage(Pipe.ControlChannelEncoding.GetBytes(Pipe.SubscriberCountAddress), Pipe.ControlChannelEncoding.GetBytes("ADDSUBSCRIBER"), pub); if (input == "Exit") { break; } Console.WriteLine("message sent"); } Console.WriteLine("message sent enter to exit=>"); input = Console.ReadLine(); } } return(input); }
public static void Main(string[] args) { using (var context = ZmqContext.Create()) { using (ZmqSocket publisher = context.CreateSocket(SocketType.PUB)) { publisher.Bind("tcp://*:5556"); var randomizer = new Random(DateTime.Now.Millisecond); while (true) { // Get values that will fool the boss int zipcode = randomizer.Next(0, 100000); int temperature = randomizer.Next(-80, 135); int relativeHumidity = randomizer.Next(10, 60); string update = zipcode.ToString() + " " + temperature.ToString() + " " + relativeHumidity.ToString(); // Send message to 0..N subscribers via a pub socket publisher.Send(update, Encoding.Unicode); } } } }
protected virtual void SendCommand(IMessageContext messageContext) { try { var frame = messageContext.GetFrame(); ZmqSocket commandSender = null; if (CommandSenders.Count == 1) { commandSender = CommandSenders[0]; } else if (CommandSenders.Count > 1) { var commandKey = messageContext.Key; int keyHashCode = !string.IsNullOrWhiteSpace(commandKey) ? commandKey.GetUniqueCode() : messageContext.MessageID.GetUniqueCode(); commandSender = CommandSenders[keyHashCode % CommandSenders.Count]; } if (commandSender == null) { return; } var status = commandSender.SendFrame(frame); _Logger.InfoFormat("send commandID:{0} length:{1} send status:{2}", messageContext.MessageID, frame.BufferSize, status.ToString()); } catch (Exception ex) { _Logger.Error(ex.GetBaseException().Message, ex); } }
public Service1(ZmqSocket socket) { _timer.Interval = 3000; _socket = socket; InitializeComponent(); }
public static void Main(string[] args) { using (var context = ZmqContext.Create()) { using (ZmqSocket receiver = context.CreateSocket(SocketType.PULL), controller = context.CreateSocket(SocketType.PUB)) { receiver.Bind("tcp://*:5558"); controller.Bind("tcp://*:5559"); // Wait for start of batch receiver.Receive(Encoding.Unicode); var stopwatch = new Stopwatch(); stopwatch.Start(); const int tasksToConfirm = 100; for (int taskNumber = 0; taskNumber < tasksToConfirm; taskNumber++) { string message = receiver.Receive(Encoding.Unicode); Console.WriteLine(taskNumber % 10 == 0 ? ":" : "."); } stopwatch.Stop(); Console.WriteLine("Total elapsed time: {0}", stopwatch.ElapsedMilliseconds); controller.Send("KILL", Encoding.Unicode); } } }
private ZmqSocket CreateSocket() { var socket = new ZmqSocket(_context, ZmqSocketType.PUSH); socket.SetOption(ZmqSocketOption.SNDHWM, _options.SendHighWaterMark); socket.SetOption(ZmqSocketOption.SNDTIMEO, (int)_options.SendTimeout.TotalMilliseconds); if (_options.KeepAlive != null) { socket.SetOption(ZmqSocketOption.TCP_KEEPALIVE, _options.KeepAlive.Enabled ? 1 : 0); if (_options.KeepAlive.KeepAliveTimeout != null) { socket.SetOption(ZmqSocketOption.TCP_KEEPALIVE_IDLE, (int)_options.KeepAlive.KeepAliveTimeout.Value.TotalSeconds); } if (_options.KeepAlive.KeepAliveInterval != null) { socket.SetOption(ZmqSocketOption.TCP_KEEPALIVE_INTVL, (int)_options.KeepAlive.KeepAliveInterval.Value.TotalSeconds); } } socket.SetOption(ZmqSocketOption.ROUTING_ID, Encoding.ASCII.GetBytes(PeerId.ToString())); return(socket); }
internal void InitSender() { if (null == this.producerEndpoint) { this.producerEndpoint = this.session.Connection.GetProducer(); } }
public static string SetID(ZmqSocket client, Encoding unicode) { var str = client.GetHashCode().ToString(); client.Identity = unicode.GetBytes(str); return(str); }
/// <summary> /// Releases the unmanaged resources used by the RpcServer, and optionally disposes of the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { //释放拖管对象 } //释放非托管对象 //已经不运行 _isRunning = false; //默认连接上 _isConnected = true; Send(RockContext.LocalVIP, _localPort, _emptyFrame);//使服务关闭 //关闭socket池 for (int i = _socketQueue.Count; i > 0; i--) { ZmqSocket socket = _socketQueue.Dequeue() as ZmqSocket; socket.Dispose(); } RockContext.UnregisterPort(_localPort); } _disposed = true; }
private void Recevier() { using (ZmqSocket monitorSocket = _context.CreateSocket(SocketType.DEALER)) { monitorSocket.Identity = BitConverter.GetBytes(_localPort); monitorSocket.SendHighWatermark = 10000000; _isConnected = false; while (!_isConnected) { try { monitorSocket.Connect(_inprocHost); _isConnected = true; } catch { Thread.Sleep(500); } } while (_isRunning) { ZmqMessage zmqMessage = monitorSocket.ReceiveMessage(); // 执行Rpc调用任务 Action <object> dealRpcAction = DealMessage; Task.Factory.StartNew(dealRpcAction, zmqMessage); } } }
public static KvMsg Receive(ZmqSocket subscriber) { var key = subscriber.Receive(Encoding.Unicode); var sequence = BitConverter.ToInt64(Encoding.Unicode.GetBytes(subscriber.Receive(Encoding.Unicode)), 0); var body = subscriber.Receive(Encoding.Unicode); return new KvMsg(sequence, key, body); }
public ZeroMqMessagePublisher(ZmqContext context) { Console.WriteLine("Hey there"); _pub = context.CreateSocket(SocketType.PUB); _pub.Bind("tcp://*:5555"); Console.WriteLine("Hello"); }
public void CreateCommandReceiverSocket(string endpoint) { _receptionSocket = _context.CreateSocket(SocketType.PULL); _receptionSocket.Linger = TimeSpan.FromSeconds(1); _receptionSocket.ReceiveHighWatermark = 30000; _receptionSocket.Bind(endpoint); _logger.DebugFormat("Command processor socket bound to {0}", endpoint); }
public void CreateReceiveSocket() { m_SubscribeSocket = m_Context.CreateSocket(SocketType.SUB); m_SubscribeSocket.SubscribeAll(); m_SubscribeSocket.Connect("epgm://239.1.1.1:9500"); m_SubscribeSocket.Bind("tcp://*:9501"); m_SubscribeSocket.Connect("inproc://Local"); }
public void Receive(ZmqSocket ZmqSocket) { var zmqMessage = ZmqSocket.ReceiveMessage(); foreach (var frame in zmqMessage) { frames.Insert(0, frame.Buffer); } }
public void Send(ZmqSocket socket) { for (int index = frames.Count - 1; index > 0; index--) { socket.SendMore(frames[index]); } socket.Send(frames[0]); }
public void ConnectSocket() { if (_socket != null) { return; } _socket = _context.CreateSocket(SocketType.SUB); _socket.Subscribe(new byte[] {}); _socket.Connect(_endpoint); }
public void Start() { _context = ZmqContext.Create(); _commandReceiver = _context.CreateSocket(SocketType.REP); _commandReceiver.Bind("tcp://*:7777"); _dequeueReceiver = _context.CreateSocket(SocketType.PUB); _dequeueReceiver.Bind("tcp://*:7778"); StartListener(); }
public override void Bind(ZmqSocket socket, ZeroRoute config) { ZeroLog.LogInfo("push bind...."); foreach (var endPoint in config.ConnectEndPoints()) { socket.Connect(endPoint); ZeroLog.LogInfo("push bind...."); } }
internal SocketEventArgs(ZmqSocket socket, PollEvents readyEvents) { if (socket == null) { throw new ArgumentNullException("socket"); } this.Socket = socket; this.ReceiveReady = readyEvents.HasFlag(PollEvents.PollIn); this.SendReady = readyEvents.HasFlag(PollEvents.PollOut); }
public void Dispose() { if (_socket != null) { _socket.Dispose(); _socket = null; } if (_context != null) { _context.Dispose(); _context = null; } }
private static void ReceiverPollInHandler(ZmqSocket receiver, ZmqSocket sender) { string task = receiver.Receive(Encoding.Unicode); // Simple progress indicator for the viewer; Console.WriteLine("{0}.", task); int sleepTime = Convert.ToInt32(task); Thread.Sleep(sleepTime); // Send 'result' to the sink sender.Send("", Encoding.Unicode); }
/// <summary> /// Create a new Host Interface server. /// </summary> /// <param name="port">Port to bind to.</param> public HostInterface(int port, INodeController controller) { log.Info("Host server interface launching..."); this.port = port; context = ZmqContext.Create(); server = context.CreateSocket(SocketType.ROUTER); server.TcpKeepalive = TcpKeepaliveBehaviour.Enable; this.controller = controller; var controllerPortal = new ControllerPortal(); controllerPortal.SetNodeID(0); controller.Initialize(controllerPortal); Instance = this; }
protected override void Dispose(bool disposing) { if (disposing && socket != null) { socket.Dispose(); socket = null; } if (disposing && context != null) { context.Dispose(); context = null; } }
/// <summary> /// Initialize the node /// </summary> /// <param name="portal">access portal to the Matrix. should be stored.</param> public void Initialize(IMatrixPortal portal) { log.Info("Launching a new game server node on port "+Settings.Default.GameInterfacePort); server = MmoZmq.context.CreateSocket(ZeroMQ.SocketType.ROUTER); log.Debug(MmoEncrypt.Keys.Count+" encryption keys."); controller = portal.GetNodeProxy<IMMOCluster>(); log.Debug("Realms count: "+MmoWorld.Realms.Count); status = 1; serverTask = Task.Factory.StartNew(ServerThread); }
public GrapevineSender(ZmqContext context, string address, IMessageSerializer serializer) { _serializer = serializer; _scheduler = new EventLoopScheduler(); _socket = context.CreateSocket(SocketType.PUB); _socket.Connect(address); _messages = new Subject<ZmqMessage>(); _messageDispatcher = _messages .SubscribeOn(_scheduler) .ObserveOn(_scheduler) .Subscribe(msg => _socket.SendMessage(msg)); }
public void Start() { if (!string.IsNullOrWhiteSpace(_PubEndPoint)) { ZmqEventPublisher = ZeroMessageQueue.ZmqContext.CreateSocket(SocketType.PUB); ZmqEventPublisher.Bind(_PubEndPoint); using (var messageStore = IoCFactory.Resolve<IMessageStore>()) { messageStore.GetAllUnPublishedEvents() .ForEach(eventContext => MessageQueue.Add(eventContext)); } _WorkTask = Task.Factory.StartNew(PublishEvent, TaskCreationOptions.LongRunning); } }
public ZmqEndPoint Bind() { _socket = CreateSocket(); _endPoint = new ZmqEndPoint(_originalEndpoint.Value); if (_endPoint.HasRandomPort) _endPoint.SelectRandomPort(_peerId, _environment); _socket.Bind(_endPoint.Value); var endPointWithIp = new ZmqEndPoint(_socket.LastEndpoint); _logger.InfoFormat("Socket bound, Inbound EndPoint: {0}", endPointWithIp.Value); return endPointWithIp; }
protected override OpStatus OnSendComplete(ZmqSocket Socket) { // Request-replay socket (REQ) should immideatly receive message just after 'send' #if DEBUG System.Console.WriteLine("[RequestReplaySocket] Before receiveng the package"); System.Console.WriteLine("[RequestReplaySocket] Current thread ID:" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()); #endif ZmqMessage okMessage = Socket.ReceiveMessage(TimeSpan.FromSeconds(1)); #if DEBUG System.Console.WriteLine("[RequestReplaySocket] Replay message was received. Status is: " + Socket.ReceiveStatus.ToString()); #endif return Socket.ReceiveStatus.Convert(); }
/// <summary> /// Add a socket that will be polled for input/output events, depending on its capabilities. /// </summary> /// <param name="socket">The <see cref="ZmqSocket"/> to poll.</param> /// <exception cref="ArgumentNullException"><paramref name="socket"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="socket"/> has no event handlers.</exception> public void AddSocket(ZmqSocket socket) { if (socket == null) { throw new ArgumentNullException("socket"); } var pollEvents = socket.GetPollEvents(); if (pollEvents == PollEvents.None) { throw new ArgumentOutOfRangeException("socket", "Unable to add socket without at least one handler."); } _pollableSockets.Add(new PollItem(socket.SocketHandle, pollEvents), socket); }