예제 #1
1
 /// <summary>
 ///     setup the client with standard values
 ///     verbose == false
 ///     timeout == 2500
 ///     reties  == 3
 /// </summary>
 private MDPClient()
 {
     m_ctx = NetMQContext.Create ();
     m_client = null;
     Timeout = TimeSpan.FromMilliseconds (2500);
     Retries = 3;
     m_connected = false;
 }
예제 #2
0
 public FeedZmQPublisher(string address, ILog log)
 {
     _log = log;
     _context = NetMQContext.Create();
     _socket = _context.CreatePushSocket();
     _socket.Bind(address);
 }
예제 #3
0
 internal Socket(NetMQSocket socket, SocketConfiguration config)
 {
     socket.Options.Linger = config.Linger;
     socket.Options.ReceiveHighWatermark = config.ReceivingHighWatermark;
     socket.Options.SendHighWatermark = config.SendingHighWatermark;
     this.socket = socket;
 }
예제 #4
0
 public Transport(NetMQSocket value) : this()
 {
     if (value != null)
     {
         this.socket = value;
     }
 }
        private void SetupPublisher()
        {
            Open(0);

            _publisherSocket = _context.CreatePublisherSocket();
            _publisherSocket.Bind(_configuration.PublisherAddress);
        }
예제 #6
0
파일: DeviceBase.cs 프로젝트: awb99/netmq
        /// <summary>
        /// Create a new instance of the <see cref="DeviceBase"/> class.
        /// </summary>
        /// <param name="poller">the <see cref="INetMQPoller"/> to use for detecting when messages are available</param>
        /// <param name="frontendSocket">
        /// A <see cref="NetMQSocket"/> that will pass incoming messages to <paramref name="backendSocket"/>.
        /// </param>
        /// <param name="backendSocket">
        /// A <see cref="NetMQSocket"/> that will receive messages from (and optionally send replies to) <paramref name="frontendSocket"/>.
        /// </param>
        /// <param name="mode">the <see cref="DeviceMode"/> (either Blocking or Threaded) for this device</param>
        /// <exception cref="ArgumentNullException">frontendSocket must not be null.</exception>
        /// <exception cref="ArgumentNullException">backendSocket must not be null.</exception>
        protected DeviceBase(INetMQPoller poller,  NetMQSocket frontendSocket,  NetMQSocket backendSocket, DeviceMode mode)
        {
            m_isInitialized = false;

            if (frontendSocket == null)
                throw new ArgumentNullException("frontendSocket");

            if (backendSocket == null)
                throw new ArgumentNullException("backendSocket");

            FrontendSocket = frontendSocket;
            BackendSocket = backendSocket;

            FrontendSetup = new DeviceSocketSetup(FrontendSocket);
            BackendSetup = new DeviceSocketSetup(BackendSocket);

            m_poller = poller;

            FrontendSocket.ReceiveReady += FrontendHandler;
            BackendSocket.ReceiveReady += BackendHandler;

            m_poller.Add(FrontendSocket);
            m_poller.Add(BackendSocket);

            m_runner = mode == DeviceMode.Blocking
                ? new DeviceRunner(this)
                : new ThreadedDeviceRunner(this);
        }
예제 #7
0
 public void Disconnect()
 {
     _socket.ReceiveReady -= socket_ReceiveReady;
     _socket.Options.Linger = TimeSpan.FromSeconds(0);
     _socket.Dispose();
     _socket = null;
 }
예제 #8
0
 public TcpGateway(NetMQContext ctx, string endpoint, MessageProcessor processor)
 {
     _ctx = ctx;
     _endpoint = endpoint;
     _processor = processor;
     _socket = connect();
 }
예제 #9
0
		public async Task Start ()
		{
			ThrowIfDisposed ();
			var ct = cancellationTokenSource.Token;

			nmqPoller = new Poller ();
			nmqScheduler = new NetMQScheduler (nmqContext, nmqPoller);
			nmqServer = nmqContext.CreateResponseSocket ();
			nmqServer.Bind (Address.AbsoluteUri.TrimEnd ('/'));

			serverTask = Task.Factory.StartNew (() => {
				ct.ThrowIfCancellationRequested ();

				while (true) {
					if (ct.IsCancellationRequested) {
						// clean up here
						ct.ThrowIfCancellationRequested ();
					}
					var msg = nmqServer.Receive ();
					var request = Request.Deserialize (msg);
					var result = Handle (request);

					byte[] output_buffer = result.Serialize ();
					nmqServer.Send (output_buffer);
				}
			}, ct);

			await serverTask;
		}
        public void ConnectOrBindAddress(NetMQSocket socket)
        {
            var port = socket.BindRandomPort(Uri.AbsoluteUri.TrimEnd('/'));
            var address = $"{Uri.Scheme}://{Uri.Host}:{port}";

            Uri = new Uri(address);
        }
예제 #11
0
파일: MDPClient.cs 프로젝트: cjkao/netmq
 /// <summary>
 ///     setup the client with standard values
 ///     verbose == false
 ///     timeout == 2500
 ///     reties  == 3
 /// </summary>
 private MDPClient ()
 {
     m_client = null;
     Timeout = TimeSpan.FromMilliseconds (2500);
     Retries = 3;
     m_connected = false;
 }
 internal NmqMessageSender(Uri serviceUri)
 {
     context = NetMQContext.Create();
     socket = context.CreateRequestSocket();
     var address = string.Format("tcp://{0}:{1}", serviceUri.Host, serviceUri.Port);
     socket.Connect(address);
 }
예제 #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Logit.Zmq.OutputWriter"/> class.
 /// </summary>
 /// <param name="zt">ØMQ Transport to use.</param>
 public OutputWriter(Transport zt) : base(CultureInfo.InvariantCulture)
 {
     if (zt != null)
     {
         this.socket = zt.Socket;
     }
 }
예제 #14
0
파일: Poller.cs 프로젝트: bubbafat/netmq
        public void RemoveSocket(NetMQSocket socket)
        {
            socket.EventsChanged -= OnSocketEventsChanged;

            m_sockets.Remove(socket);
            m_isDirty = true;
        }
예제 #15
0
        internal WebSocketClient(NetMQSocket streamSocket, byte[] identity)
        {
            m_state = WebSocketClientState.Closed;
            m_streamSocket = streamSocket;
            m_outgoingMessage = null;

            Identity = identity;
        }
예제 #16
0
 /// <summary>
 /// Create a new instance of a Proxy (NetMQ.Proxy)
 /// with the given sockets to serve as a front-end, a back-end, and a control socket.
 /// </summary>
 /// <param name="frontend">the socket that messages will be forwarded from</param>
 /// <param name="backend">the socket that messages will be forwarded to</param>
 /// <param name="control">this socket will have messages also sent to it - you can set this to null if not needed</param>
 /// <param name="poller">an optional external poller to use within this proxy</param>
 public Proxy([NotNull] NetMQSocket frontend, [NotNull] NetMQSocket backend, [CanBeNull] NetMQSocket control = null, Poller poller = null)
 {
     m_frontend = frontend;
     m_backend = backend;
     m_control = control;
     m_externalPoller = poller != null;
     m_poller = poller;
 }
예제 #17
0
 protected override void DoServer(NetMQSocket socket, int messageSize)
 {
     for (int i = 0; i < Iterations; i++)
     {
         byte[] message = socket.Receive();
         socket.Send(message);
     }
 }
		public void Start ()
		{
			ThrowIfDisposed ();
			nmqPoller = new Poller ();
			nmqClient = nmqContext.CreateRequestSocket ();
			nmqClient.Connect (Address.AbsoluteUri.TrimEnd ('/'));
			nmqScheduler = new NetMQScheduler (nmqContext, nmqPoller);
			Task.Factory.StartNew (() => nmqPoller.Start (), TaskCreationOptions.LongRunning);
		}
예제 #19
0
 public void Start()
 {
     poller = new Poller();
     clientSocket = context.CreateDealerSocket();
     clientSocket.ReceiveReady += clientSocket_ReceiveReady;
     clientSocket.Connect(address);
     scheduler = new NetMQScheduler(context, poller);
     Task.Factory.StartNew(poller.Start, TaskCreationOptions.LongRunning);
 }
예제 #20
0
 public SingleThreadedZeroMqGateway(string endpoint, TimeSpan reaperInterval)
 {
     Log.DebugFormat("[STZMG] Starting. Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);
     _ctx = NetMQContext.Create();
     _endpoint = endpoint;
     _reaperInterval = reaperInterval;
     _socket = connect();
     _reapTime = DateTime.Now.Add(reaperInterval);
 }
예제 #21
0
 private void InitZmq()
 {
     if (_ctx == null)
     {
         _ctx = NetMQContext.Create();
         _socket = _ctx.CreatePublisherSocket();
         var address = string.Format("{0}:{1}", _host, _port);
         _socket.Bind(address);
     }
 }
		public MessageHelper(string address, string topic)
		{
			_context = NetMQContext.Create();
			_subscribeSocket = _context.CreateSubscriberSocket();
			_subscribeSocket.Connect(address);
			_subscribeSocket.ReceiveReady += SubscribeSocketOnReceiveReady;
			_subscribeSocket.Subscribe(topic);
			_poller = new Poller();
			_poller.AddSocket(_subscribeSocket);
			Task.Factory.StartNew(_poller.Start);
		}
예제 #23
0
        public static bool Send(Message message, NetMQSocket socket)
        {
            Send(message.UUID, socket);
            Send(Delimeter, socket);
            Send(string.Empty, socket);
            Send(JsonSerializer.Serialize(message.Header), socket);
            Send(JsonSerializer.Serialize(message.ParentHeader), socket);
            Send(JsonSerializer.Serialize(message.MetaData), socket);
            Send(message.Content, socket, false);

            return true;
        }
예제 #24
0
        public Action<NetMQMessage> Send(NetMQSocket socket, PendingResRequest pendingRequest, Guid requestId)
        {
            var pending = (PendingResRequest<QueryEventsForStreamResponse>) pendingRequest;
            var msg = new NetMQMessage();
            msg.AppendEmptyFrame();
            msg.Append(ResProtocol.ResClient01);
            msg.Append(ResCommands.QueryEventsByStream);
            msg.Append(requestId.ToByteArray());
            msg.Append(_context);
            msg.Append(_stream);
            msg.Append(_fromVersion.ToNetMqFrame());
            msg.Append(_maxVersion.ToNetMqFrame());

            socket.SendMultipartMessage(msg);

            return m =>
            {
                var command = m.Pop().ConvertToString();

                if (command == ResCommands.Error)
                {
                    var errorCode = m.Pop().ConvertToString();
                    var errorDetails = m.Pop().ConvertToString();
                    ErrorResolver.RaiseException(errorCode, errorDetails, pending.SetException);
                    return;
                }

                if (command != ResCommands.QueryEventsByStreamResponse)
                    pending.SetException(new UnsupportedCommandException(command));

                var count = m.PopInt32();

                var events = new EventInStorage[count];

                for (var i = 0; i < count; i++)
                {
                    var id = new Guid(m.Pop().ToByteArray());
                    var streamId = m.Pop().ConvertToString();
                    var context = m.Pop().ConvertToString();
                    var sequence = m.PopInt64();
                    var timestamp = m.PopDateTime();;
                    var type = m.PopString();
                    var headers = m.PopStringOrNull();
                    var body = m.PopString();

                    events[i] = new EventInStorage(context, streamId, sequence, type, id, headers, body, timestamp);
                }

                var result = new QueryEventsForStreamResponse(_context, _stream, events);
                pending.SetResult(result);
            };
        }
예제 #25
0
        private NetMQMonitor CreateMonitor(NetMQContext context, NetMQSocket socket, Poller poller)
        {
            var monitor = new NetMQMonitor(context, socket, $"inproc://{Guid.NewGuid()}.inproc",
                SocketEvents.Connected | SocketEvents.Disconnected | SocketEvents.ConnectRetried);

            monitor.Connected += Monitor_Connected;
            monitor.Disconnected += Monitor_Disconnected;
            monitor.ConnectRetried += Monitor_ConnectRetried;

            monitor.AttachToPoller(poller);

            return monitor;
        }
예제 #26
0
        public TestReciever Start()
        {
            _context = NetMQContext.Create();
            _socket = _context.CreatePullSocket();
            _socket.Connect(_publisherAddress);

            Task.Run(() =>
            {
                Recieve();
            });

            return this;
        }
예제 #27
0
파일: Poller.cs 프로젝트: bubbafat/netmq
        public void AddSocket(NetMQSocket socket)
        {
            if (m_sockets.Contains(socket))
            {
                throw new ArgumentException("Socket already added to poller");
            }

            m_sockets.Add(socket);

            socket.EventsChanged += OnSocketEventsChanged;

            m_isDirty = true;
        }
예제 #28
0
        public void ProcessMessage(NetMQMessage message, NetMQSocket socket)
        {
            if (message.FrameCount < 3)
                throw new MalformedMessageReceivedException(message.FrameCount);

            var sender = message.PopUntilEmptyFrame();
            var protocolFrame = message.Pop();
            var protocol = protocolFrame.ConvertToString();
            ensureProtocol(protocol);
            var command = message.Pop().ConvertToString();

            _dispatcher.Dispatch(command, sender, message);
        }
예제 #29
0
파일: Proxy.cs 프로젝트: somdoron/netmq
        /// <summary>
        /// Create a new instance of a Proxy (NetMQ.Proxy)
        /// with the given sockets to serve as a front-end, a back-end, and a control socket.
        /// </summary>
        /// <param name="frontend">the socket that messages will be forwarded from</param>
        /// <param name="backend">the socket that messages will be forwarded to</param>
        /// <param name="controlIn">this socket will have incoming messages also sent to it - you can set this to null if not needed</param>
        /// <param name="controlOut">this socket will have outgoing messages also sent to it - you can set this to null if not needed</param>
        /// <param name="poller">an optional external poller to use within this proxy</param>
        public Proxy([NotNull] NetMQSocket frontend, [NotNull] NetMQSocket backend, [CanBeNull] NetMQSocket controlIn, [CanBeNull] NetMQSocket controlOut, [CanBeNull] INetMQPoller poller = null)
        {
            if (poller != null)
            {
                m_externalPoller = true;
                m_poller = poller;
            }

            m_frontend = frontend;
            m_backend = backend;
            m_controlIn = controlIn;
            m_controlOut = controlOut ?? controlIn;
        }
예제 #30
0
        public Subscriber(params string[] messageKeys)
        {
            if (messageKeys != null && messageKeys.Length > 0)
                subscribeTo.AddRange(messageKeys.ToList());

            context = NetMQContext.Create();
            server = context.CreateSubscriberSocket();
            server.Connect("tcp://127.0.0.1:5003");

            subscribeTo.ForEach(server.Subscribe);

            Thread.Sleep(500);
        }
예제 #31
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            if (disposing && context != null)
            {
                context.Dispose();
                context = null;
            }
        }
예제 #32
0
        protected override long DoClient(NetMQSocket socket, int messageSize)
        {
            var msg = new byte[messageSize];

            var watch = Stopwatch.StartNew();

            for (int i = 0; i < Iterations; i++)
            {
                socket.Send(msg);
                socket.SkipFrame(); // ignore response
            }

            return(watch.ElapsedTicks);
        }
        protected override void DoWork(NetMQSocket socket)
        {
            var received = socket.ReceiveMultipartStrings();

            Console.WriteLine("Worker received: ");

            for (var i = 0; i < received.Count; i++)
            {
                var r = received[i];
                Console.WriteLine("{0}: {1}", i, r);
            }

            Console.WriteLine("------");
        }
예제 #34
0
        public NetMQMonitor(NetMQContext context, NetMQSocket monitoredSocket, string endpoint, SocketEvent eventsToMonitor)
        {
            Endpoint = endpoint;
            Timeout  = TimeSpan.FromSeconds(0.5);

            ZMQ.SocketMonitor(monitoredSocket.SocketHandle, Endpoint, eventsToMonitor);

            MonitoringSocket = context.CreatePairSocket();
            MonitoringSocket.Options.Linger = TimeSpan.Zero;

            MonitoringSocket.ReceiveReady += Handle;

            m_isOwner = true;
        }
예제 #35
0
        protected override void DoWork(NetMQSocket socket)
        {
            var received = socket.ReceiveStringMessages().ToList();

            Console.WriteLine("Pulled: ");

            for (var i = 0; i < received.Count; i++)
            {
                var r = received[i];
                Console.WriteLine("{0}: {1}", i, r);
            }

            Console.WriteLine("------");
        }
예제 #36
0
        /// <summary>
        ///     setup the client with standard values
        ///     verbose == false
        ///     Connect the client to broker
        /// </summary>
        private MDPClientAsync()
        {
            m_client    = null;
            m_connected = false;

            m_poller = new NetMQPoller();
            Timeout  = m_defaultTimeOut;

            m_timer        = new NetMQTimer(Timeout);
            m_timer.Enable = false;
            m_poller.Add(m_timer);
            m_timer.Elapsed += (s, e) => OnProcessTimeOut();
            m_poller.RunAsync();
        }
예제 #37
0
        /// <summary>
        /// Create a new instance of a Proxy (NetMQ.Proxy)
        /// with the given sockets to serve as a front-end, a back-end, and a control socket.
        /// </summary>
        /// <param name="frontend">the socket that messages will be forwarded from</param>
        /// <param name="backend">the socket that messages will be forwarded to</param>
        /// <param name="controlIn">this socket will have incoming messages also sent to it - you can set this to null if not needed</param>
        /// <param name="controlOut">this socket will have outgoing messages also sent to it - you can set this to null if not needed</param>
        /// <param name="poller">an optional external poller to use within this proxy</param>
        /// <param name="proxyBetween"> user provided proxy function</param>
        public NetmqProxy([NotNull] NetMQSocket frontend, [NotNull] NetMQSocket backend, [CanBeNull] NetMQSocket controlIn, [CanBeNull] NetMQSocket controlOut, [CanBeNull] INetMQPoller poller = null, Action <IReceivingSocket, IOutgoingSocket> proxyBetween = null)
        {
            if (poller != null)
            {
                m_externalPoller = true;
                m_poller         = poller;
            }

            m_frontend     = frontend;
            m_backend      = backend;
            m_controlIn    = controlIn;
            m_controlOut   = controlOut ?? controlIn;
            m_ProxyBetween = proxyBetween;
        }
예제 #38
0
        public bool Send(Message message, NetMQSocket socket)
        {
            string hmac = this._signatureValidator.CreateSignature(message);

            Send(message.UUID, socket);
            Send(Delimeter, socket);
            Send(hmac, socket);
            Send(JsonSerializer.Serialize(message.Header), socket);
            Send(JsonSerializer.Serialize(message.ParentHeader), socket);
            Send(JsonSerializer.Serialize(message.MetaData), socket);
            Send(message.Content, socket, false);

            return(true);
        }
예제 #39
0
        public SharpDBConnection GetConnection()
        {
            NetMQSocket socket = m_context.CreateRequestSocket();

            socket.Options.CopyMessages = false;
            socket.Options.Linger       = TimeSpan.FromSeconds(5);
            socket.Connect(ConnectionString);

            var connection = new SharpDBConnection(this, socket, SerializerFactory());

            m_connections.Add(connection);

            return(connection);
        }
예제 #40
0
        public static void Blow(string song, string notes)
        {
            new Thread(() => {
                using (NetMQSocket request_socket = context.CreateRequestSocket()) {
                    request_socket.Connect(string.Format("tcp://{0}:{1}", Address, RequestPort));
                    request_socket.SendMore("blow").SendMore(song).Send(notes);

                    string response = request_socket.ReceiveString();
                    Console.WriteLine("[request_socket] Response: {0}", response);

                    request_socket.Close();
                    request_socket.Dispose();
                }
            }).Start();
        }
예제 #41
0
        public Task StartAsync(HostingApplication hostingApplication, CancellationToken cancellationToken)
        {
            _routerSocket = new RouterSocket();
            _routerSocket.Bind($"tcp://{_hostingOptions.Host}");
            _routerSocket.ReceiveReady += RouterSocket_ReceiveReady;
            _dealerSocket = new DealerSocket();
            _dealerSocket.Bind(INPROC_SERVER_URL);
            _dealerSocket.ReceiveReady += DealerSocket_ReceiveReady;
            _poller = new NetMQPoller {
                _routerSocket, _dealerSocket
            };
            _poller.RunAsync();

            return(Task.CompletedTask);
        }
예제 #42
0
        public virtual bool Return(NetMQSocket connection)
        {
            if (Interlocked.Increment(ref _count) <= _maxSize)
            {
                _pool.Enqueue(connection);

                return(true);
            }

            Interlocked.Decrement(ref _count);

            Debug.Assert(_maxSize == 0 || _pool.Count <= _maxSize);

            return(false);
        }
예제 #43
0
        public void Dispose()
        {
            StopServer();

            if (_routerSocket != null)
            {
                _routerSocket.Dispose();
                _routerSocket = null;
            }
            if (_context != null)
            {
                _context.Dispose();
                _context = null;
            }
        }
예제 #44
0
    public ReliableExternalClient(string srvAdress_, TimeSpan timeout_, uint retries_)
    {
        socket = null;

        srvAddress = srvAdress_;
        timeout    = timeout_;
        retries    = retries_;

        if (timeout.TotalMilliseconds < min_trysend_ms)
        {
            UnityEngine.Debug.Log(
                String.Format("Timeout {0} has to be greater than min_trysend_time {1} ms",
                              timeout.TotalMilliseconds, min_trysend_ms));
        }
    }
예제 #45
0
        protected override long DoClient(NetMQSocket socket, int messageSize)
        {
            var msg   = new Msg();
            var watch = Stopwatch.StartNew();

            for (int i = 0; i < Iterations; i++)
            {
                msg.InitGC(new byte[messageSize], messageSize);
                socket.Send(ref msg, more: false);
                socket.Receive(ref msg);
                msg.Close();
            }

            return(watch.ElapsedTicks);
        }
예제 #46
0
 public NetmqTransportClient(ISerializer <string> serializer, EndPoint endPoint)
 {
     _serializer   = serializer ?? throw new ArgumentNullException(nameof(serializer));
     _endPoint     = endPoint ?? throw new ArgumentNullException(nameof(endPoint));
     Identity      = Guid.NewGuid().ToString();
     _dealerSocket = new DealerSocket($"tcp://{endPoint}");
     _dealerSocket.Options.Identity = Encoding.UTF8.GetBytes(Identity);
     _dealerSocket.ReceiveReady    += DealerSocket_ReceiveReady;
     _routerSocket = new RouterSocket($"inproc://{Identity}");
     _routerSocket.ReceiveReady += RouterSocket_ReceiveReady;
     _poller = new NetMQPoller {
         _dealerSocket, _routerSocket
     };
     _poller.RunAsync();
 }
예제 #47
0
        public string Request(string service, string msg, int timeoutmsec)
        {
            string      resp    = string.Empty;
            LinkAddress address = config.ReqRep.FindLinkAddress(service);

            if (address == null)
            {
                return(resp);
            }

            bool   pollResult = false;
            string requestId  = Guid.NewGuid().ToString();

            using (NetMQContext context = NetMQContext.Create())
            {
                NetMQSocket client = context.CreateRequestSocket();
                client.Options.Linger   = TimeSpan.Zero;
                client.Options.Identity = Encoding.UTF8.GetBytes(requestId);
                client.Connect(address.Address);
                try
                {
                    byte[] data = Encoding.UTF8.GetBytes(msg);
                    client.Send(data);
                }
                catch (Exception)
                {
                    client.Disconnect(address.Address);
                    client.Dispose();
                    return(resp);
                }

                client.ReceiveReady += ClientOnReceiveReady;
                pollResult           = client.Poll(TimeSpan.FromMilliseconds(timeoutmsec));
                client.ReceiveReady -= ClientOnReceiveReady;
                client.Disconnect(address.Address);
                client.Dispose();
            }

            if (pollResult)
            {
                if (responseMsgs.ContainsKey(requestId))
                {
                    responseMsgs.TryRemove(requestId, out resp);
                }
            }

            return(resp);
        }
예제 #48
0
        public void Start(string configFile)
        {
            config = ServiceConfig.FromXml(configFile);
            log.DebugFormat("Start from {0}", configFile);

            if (config.PushPull != null)
            {
                log.InfoFormat("Starting listening for Pull: {0}", config.PushPull.ListenAddress);
                NetMQContext ctx1 = NetMQContext.Create();
                InitLinks(ctx1, _push_links, config.PushPull, ZmqSocketType.Push);
                puller = ctx1.CreatePullSocket();
                puller.ReceiveReady += this.PullerReceiveReady;
                puller.Bind(config.PushPull.ListenAddress);
                this.source_pp = new CancellationTokenSource();
                this.token_pp  = this.source_pp.Token;
                Task newTask = Task.Factory.StartNew(this.OnPull, this.token_pp);
                this.tasks.Add(newTask);
            }
            if (config.PubSub != null)
            {
                log.InfoFormat("Starting listening for subscriber: {0}", config.PubSub.ListenAddress);
                NetMQContext ctx2 = NetMQContext.Create();
                InitLinks(ctx2, _sub_links, config.PubSub, ZmqSocketType.Sub);
                foreach (var link in _sub_links)
                {
                    link.Value.socket.ReceiveReady += SubOnReceiveReady;
                }
                publisher = ctx2.CreatePublisherSocket();
                publisher.Bind(config.PubSub.ListenAddress);
                this.source_ps = new CancellationTokenSource();
                this.token_ps  = this.source_ps.Token;
                Task newTask = Task.Factory.StartNew(this.OnSubscribe, this.token_ps);
                this.tasks.Add(newTask);
            }
            if (config.ReqRep != null)
            {
                log.InfoFormat("Starting listening for Request: {0}", config.ReqRep.ListenAddress);
                NetMQContext ctx3 = NetMQContext.Create();
                //InitLinks(ctx3, _req_links, config.ReqRep, ZmqSocketType.Req); delete by xsw 2014-09-17
                responser = ctx3.CreateResponseSocket();
                responser.ReceiveReady += this.RepReceiveReady;
                responser.Bind(config.ReqRep.ListenAddress);
                this.source_rr = new CancellationTokenSource();
                this.token_rr  = this.source_rr.Token;
                Task newTask = Task.Factory.StartNew(this.OnResponse, this.token_rr);
                this.tasks.Add(newTask);
            }
        }
    // initialized sprites
    void Start()
    {
        AsyncIO.ForceDotNet.Force();
        calImages    = new Sprite[10];
        calImages[0] = Resources.Load <Sprite>("notargets");
        calImages[1] = Resources.Load <Sprite>("targetTL");
        calImages[2] = Resources.Load <Sprite>("targetTM");
        calImages[3] = Resources.Load <Sprite>("targetTR");
        calImages[4] = Resources.Load <Sprite>("targetML");
        calImages[5] = Resources.Load <Sprite>("targetMM");
        calImages[6] = Resources.Load <Sprite>("targetMR");
        calImages[7] = Resources.Load <Sprite>("targetBL");
        calImages[8] = Resources.Load <Sprite>("targetBM");
        calImages[9] = Resources.Load <Sprite>("targetBR");

        calCount = 0;
        curCount = 0;
        gameObject.GetComponent <Image> ().sprite = calImages [calCount];
        //max coords 1180*564
        transX       = 0;
        transY       = 0;
        targetPrefab = GameObject.FindGameObjectWithTag("RaycastTarget");
        targetPrefab.SetActive(false);
        targetPrefab.layer = 2;        //ignore raycast layer
        isVisible          = false;

        AsyncIO.ForceDotNet.Force();
        //setup sockets
        //hangs????
        //http://forum.unity3d.com/threads/netmq-basic.298104/
        //must compile myself
        //https://github.com/zeromq/netmq/issues/98
        context = NetMQContext.Create();
        server  = context.CreatePublisherSocket();
        server.Bind("tcp://127.0.0.1:5556");
        client = context.CreateSubscriberSocket();
        client.Connect("tcp://127.0.0.1:5556");
        client.Subscribe("coord");
        Debug.Log(System.Environment.Version);

        /*server.SendMore("coord").Send ("200 200");
         * string top = client.ReceiveString ();
         * string message = client.ReceiveString ();
         * Debug.Log (message);
         * string[] coord = message.Split ();
         * transX = int.Parse (coord [0]);
         * transY = int.Parse (coord [1]);*/
    }
예제 #50
0
        internal KernelMessage recvMessage(NetMQSocket socket)
        {
            // receive all parts of the message
            var message   = recvAll(socket).ToArray();
            var asStrings = message.Select(s => decode(s)).ToArray();

            // find the delimiter between IDS and MSG
            var idx         = Array.IndexOf(asStrings, "<IDS|MSG>");
            var idents      = message.Take(idx).ToArray();
            var messageList = asStrings.Skip(idx + 1).Take(asStrings.Length - 1 - idx).ToArray();

            // detect a malformed message
            if (messageList.Length < 4)
            {
                throw new Exception("Malformed message");
            }

            var hmac             = messageList[0];
            var headerJson       = messageList[1];
            var parentHeaderJson = messageList[2];
            var metadata         = messageList[3];

            var contentJson = messageList.Length >= 5 ? messageList[4] : "{}";

            var header       = JsonConvert.DeserializeObject <Header>(headerJson);
            var parentHeader = JsonConvert.DeserializeObject <Header>(parentHeaderJson);
            var metaDataDict = deserializeDict(metadata);
            var content      = ShellMessages.Deserialize(header.msg_type, contentJson);

            var calculated_signature = sign(new string[] { headerJson, parentHeaderJson, metadata, contentJson });

            if (calculated_signature != hmac)
            {
                throw new Exception("Wrong message signature");
            }

            lastMessage = new KernelMessage()
            {
                Identifiers   = idents.ToList(),
                HmacSignature = hmac,
                Header        = header,
                ParentHeader  = parentHeader,
                Metadata      = metadata,
                Content       = content
            };

            return(lastMessage);
        }
예제 #51
0
        static void Main(string[] args)
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket response = context.CreateResponseSocket())
                {
                    string address = GetComputerLanIP();

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

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

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

                                Thread.Sleep(1000);
                            }

                            response.Options.Linger = TimeSpan.Zero;
                        }
                        else
                        {
                            Console.WriteLine("Wrong IP address");
                        }
                    }
                    else
                    {
                        Console.WriteLine("The port number should be greater than 0");
                    }

                    Console.WriteLine("Press ENTER to exit...");
                    Console.ReadLine();
                }
            }
        }
예제 #52
0
        protected override void StartMethod()
        {
            _zmqContext = NetMQContext.Create();
            _zmqSocket  = _zmqContext.CreateSubscriberSocket();

            if (string.IsNullOrEmpty(_subsPrefix))
            {
                _zmqSocket.Subscribe(string.Empty);
            }
            else
            {
                _zmqSocket.Subscribe(Encoding.UTF8.GetBytes(_subsPrefix));
            }

            _zmqSocket.Connect(_endPoint);
        }
예제 #53
0
        public void Ipv6ToIpv4()
        {
            using (var context = NetMQContext.Create())
                using (var localDealer = context.CreateDealerSocket())
                    using (NetMQSocket connectingDealer = context.CreateDealerSocket())
                    {
                        localDealer.Options.IPv4Only = false;
                        var port = localDealer.BindRandomPort(string.Format("tcp://*"));

                        connectingDealer.Connect(string.Format("tcp://{0}:{1}", IPAddress.Loopback, port));

                        connectingDealer.SendFrame("test");

                        Assert.AreEqual("test", localDealer.ReceiveFrameString());
                    }
        }
예제 #54
0
        protected override void DoWork(NetMQSocket socket)
        {
            var received = socket.ReceiveMultipartStrings();

            for (var i = 0; i < received.Count; i++)
            {
                if (i == received.Count - 1)
                {
                    socket.Send(received[i]);
                }
                else
                {
                    socket.SendMore(received[i]);
                }
            }
        }
예제 #55
0
        public void Initialize()
        {
            LoggingExtensions.Logging.Log.InitializeWith <LoggingExtensions.log4net.Log4NetLog>();


            //context = NetMQContext.Create();
            frontend = new ResponseSocket();  // context.CreateResponseSocket();
            backend  = new PublisherSocket(); // context.CreatePublisherSocket();
            var frontAdress   = ConfigurationManager.AppSettings["ctrl_frontendBindAddress"];
            var bakdendAdress = ConfigurationManager.AppSettings["ctrl_backendBindAddress"];

            frontend.Bind(frontAdress);
            backend.Bind(bakdendAdress);

            this.Log().Info("初始化ZeroMq完成");
        }
예제 #56
0
        internal static void Start(this NetMQSocket socket, string address, SocketType socketType)
        {
            switch (socketType)
            {
            case SocketType.Client:
                socket.Connect(address);
                break;

            case SocketType.Server:
                socket.Bind(address);
                break;

            default:
                throw new ArgumentException(string.Format("Unknown SocketType {0}", socketType), "socketType");
            }
        }
예제 #57
0
        protected override void DoClient(int id, NetMQSocket socket)
        {
            const string value    = "Hello World";
            var          expected = value + " " + id;

            Console.WriteLine("Client: {0} sending: {1}", id, expected);
            socket.Send(expected);

            Thread.Sleep(Random.Next(1, 50));

            var response = socket.ReceiveMultipartStrings();

            Assert.AreEqual(1, response.Count);
            Assert.AreEqual(expected, response[0]);
            Console.WriteLine("Client: {0} received: {1}", id, response[0]);
        }
예제 #58
0
        /// <summary>
        ///     Starts the server.
        /// </summary>
        public void StartServer()
        {
            if (ServerRunning)
            {
                return;
            }

            lock (_socketLock) {
                _socket = new ResponseSocket(_connectionString);
                _socket.ReceiveReady += SocketReceiveReady;
            }

            _poller = new NetMQPoller {
                _socket
            };
            _poller.RunAsync();
        }
예제 #59
0
        public void Start()
        {
            using (m_serverSocket = m_context.CreateResponseSocket())
            {
                foreach (var address in m_addresses)
                {
                    m_log.InfoFormat("Listening on {0}", address);
                    m_serverSocket.Bind(address);
                }
                m_serverSocket.ReceiveReady += OnMessage;

                m_poller = new Poller();
                m_poller.AddSocket(m_serverSocket);

                m_poller.Start();
            }
        }
예제 #60
0
 //? swtich to ctor with Socket and Sender?  move setup to factory?
 public SendSocket(NetMQContext context,
                   string address,
                   Func <T, byte[]> marshaller,
                   ZmqSocketType type = ZmqSocketType.Pub,
                   bool bind          = true)
 {
     _msgSender = marshaller;
     _socket    = context.CreateSocket(type);
     if (bind)
     {
         _socket.Bind(address);
     }
     else
     {
         _socket.Connect(address);
     }
 }