Пример #1
0
        private NetMQSocket InitSocket(ZmqSocketType socketType, string endPoint, bool isBind, string identity)
        {
            NetMQSocket socket = GetSocket(socketType);

            if (identity != null && identity != "")
            {
                socket.Options.Identity = Encoding.UTF8.GetBytes(identity);
            }
            socket.Options.SendHighWatermark    = 10000;
            socket.Options.ReceiveHighWatermark = 10000;
            socket.Options.Linger               = TimeSpan.Zero;
            socket.Options.TcpKeepalive         = true;
            socket.Options.TcpKeepaliveIdle     = TimeSpan.FromMinutes(1);
            socket.Options.TcpKeepaliveInterval = TimeSpan.FromSeconds(10);
            if (isBind)
            {
                socket.Bind(endPoint);
            }
            else
            {
                socket.Connect(endPoint);
            }
            SetReceive(socketType, socket);
            return(socket);
        }
Пример #2
0
        /// <summary>
        /// Performs initialization actions, bindings and connections on the socket.
        /// </summary>
        internal void Configure()
        {
            if (m_isConfigured)
            {
                return;
            }

            if (m_bindings.Count == 0 && m_connections.Count == 0)
            {
                throw new InvalidOperationException("Device sockets must bind or connect to at least one endpoint.");
            }

            foreach (var initializer in m_socketInitializers)
            {
                initializer.Invoke(m_socket);
            }

            foreach (var endpoint in m_bindings)
            {
                m_socket.Bind(endpoint);
            }

            foreach (string endpoint in m_connections)
            {
                m_socket.Connect(endpoint);
            }

            m_isConfigured = true;
        }
Пример #3
0
        private static void Main(string[] args)
        {
            using (var ctx = NetMQContext.Create())
            {
                using (NetMQSocket frontend = ctx.CreateRouterSocket(), backend = ctx.CreateDealerSocket())
                {
                    frontend.Bind(FRONTEND_ENDPOINT);
                    backend.Bind(BACKEND_ENDPOINT);

                    //Handler for messages coming in to the frontend
                    frontend.ReceiveReady += (sender, e) =>
                    {
                        var msg = frontend.ReceiveMessage();
                        backend.SendMessage(msg);     //Relay this message to the backend
                    };

                    //Handler for messages coming in to the backend
                    backend.ReceiveReady += (sender, e) =>
                    {
                        var msg = backend.ReceiveMessage();
                        frontend.SendMessage(msg);     //Relay this message to the frontend
                    };

                    using (var poller = new Poller())
                    {
                        poller.AddSocket(backend);
                        poller.AddSocket(frontend);

                        //Listen out for events on both sockets and raise events when messages come in
                        poller.Start();
                    }
                }
            }
        }
Пример #4
0
        public void BindToLocal()
        {
            var validAliasesForLocalHost = new[] { "127.0.0.1", "localhost", System.Net.Dns.GetHostName() };

            foreach (var alias in validAliasesForLocalHost)
            {
                using (NetMQContext context = NetMQContext.Create())
                {
                    using (NetMQSocket localDealer = context.CreateDealerSocket())
                    {
                        localDealer.Bind("tcp://*:5002");

                        using (NetMQSocket connectingDealer = context.CreateDealerSocket())
                        {
                            connectingDealer.Connect("tcp://" + alias + ":5002");

                            localDealer.Send("test");

                            Assert.AreEqual("test", connectingDealer.ReceiveString());
                            Console.WriteLine(alias + " connected ");
                        }
                    }
                }
            }
        }
Пример #5
0
        //public int timeLimit = 120;
        //Add option to modify this in AppOptions

        protected override void Run()
        {
            ForceDotNet.Force();
            //socket = new RequestSocket();
            //socket.Connect("tcp://localhost:5555");
            Debug.Log("Communication started");

            if (option == CommunicatorOption.RECEIVE_DATA)
            {
                socket = new RequestSocket();
                socket.Connect(address);
                //Debug.Log("Communication started");

                dataList = new List <float[]>();

                ReceiveOnePointData();
            }
            else if (option == CommunicatorOption.SEND_DATA)
            {
                socket = new ResponseSocket();
                socket.Bind(address);
                //Debug.Log("Communication started");

                CreateByteData();
                SendOnePointData();
            }
            //byte_dataList
        }
Пример #6
0
        public static void Main(string[] args)
        {
            NetMQContext context = NetMQContext.Create();
            NetMQSocket  server  = context.CreateRequestSocket();

            server.Bind("tcp://*:5555");
            NetMQMessage message = new NetMQMessage();
            NetMQMessage getmass = new NetMQMessage();

            message.Append("Hallo ");
            message.Append(40);

            Client client = new Client();
            Thread t      = new Thread(new ThreadStart(client.runClient));

            t.Start();


            while (true)
            {
                server.SendMessage(message, false);
                getmass = server.ReceiveMessage(false);
                System.Console.WriteLine(getmass.Pop().ConvertToString());
                System.Console.WriteLine(getmass.Pop().ConvertToInt32());
            }
        }
        private void SetupPublisher()
        {
            Open(0);

            _publisherSocket = _context.CreatePublisherSocket();
            _publisherSocket.Bind(_configuration.PublisherAddress);
        }
Пример #8
0
 public FeedZmQPublisher(string address, ILog log)
 {
     _log = log;
     _context = NetMQContext.Create();
     _socket = _context.CreatePushSocket();
     _socket.Bind(address);
 }
Пример #9
0
 /// <summary>
 ///
 /// </summary>
 public void Start()
 {
     m_server = new RouterSocket();
     m_server.Bind("tcp://*:" + ListnenPort);
     m_server.ReceiveReady += Server_ReceiveReady;
     m_server.SendReady    += Server_SendReady;
     m_started              = true;
     new Thread(() =>
     {
         long nextSend = 0, nextHeartBeat = 0;
         while (m_started)
         {
             var tmp = TimeSpan.FromMilliseconds(1);
             m_server.Poll(tmp);
             if (nextSend <= 0)
             {
                 SendQueue();
                 nextSend = SendInterval;
             }
             if (nextHeartBeat <= 0)
             {
                 Heartbeat();
                 nextHeartBeat = PingInterval;
             }
             nextSend      -= 10;
             nextHeartBeat -= 10;
             Thread.Sleep(10);
         }
     })
     {
         IsBackground = true
     }.Start();
 }
Пример #10
0
        public Server(ISerializer serializer, string serverUri)
        {
            _serializer   = serializer;
            _rsa          = Rsa.Create();
            _sessionCache = new SessionCache();
            _socket       = new ResponseSocket();
            _socket.Bind(serverUri);

            while (true)
            {
                var messageBytes = _socket.ReceiveFrameBytes();
                var message      = _serializer.Deserialize <SecurityLayerMessage>(messageBytes);
                switch (message.Type)
                {
                case SecurityMessageType.ClientHello:
                    HandleClientHello(message.Data);
                    break;

                case SecurityMessageType.ClientKeyExchange:
                    HandleClientKeyExchange(message.Data);
                    break;

                case SecurityMessageType.ApplicationData:
                    HandleApplicationData(message.Data);
                    break;
                }
            }
        }
Пример #11
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;
		}
Пример #12
0
            /// <summary>
            /// Initializes a new instance of the <see cref="NmqResponseQueue"/> class.
            /// </summary>
            /// <param name="context">The context.</param>
            /// <param name="port">The port.</param>
            internal NmqResponseQueue(NetMQContext context, int port)
            {
                socket = context.CreateResponseSocket();
                var address = string.Format("tcp://127.0.0.1:{0}", port);

                socket.Bind(address);
            }
Пример #13
0
        public void HasOutTest()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket server = context.CreateDealerSocket())
                {
                    server.Bind("tcp://*:5557");

                    // no client is connected so we don't have out
                    Assert.IsFalse(server.HasOut);

                    using (NetMQSocket client = context.CreateDealerSocket())
                    {
                        Assert.IsFalse(client.HasOut);

                        client.Connect("tcp://localhost:5557");

                        Thread.Sleep(100);

                        // client is connected so server should have out now, client as well
                        Assert.IsTrue(server.HasOut);
                        Assert.IsTrue(client.HasOut);
                    }

                    Thread.Sleep(100);

                    // client is disposed,server shouldn't have out now
                    Assert.IsFalse(server.HasOut);
                }
            }
        }
Пример #14
0
        void CreateServer()
        {
            switch (_type)
            {
            case ServerType.Response:
                _serverSocket = _context.CreateResponseSocket(); break;

            case ServerType.Pub:
                _serverSocket = _context.CreatePushSocket(); break;

            case ServerType.Router:
                _serverSocket = _context.CreateRouterSocket(); break;

            case ServerType.Stream:
                _serverSocket = _context.CreateStreamSocket(); break;

            case ServerType.Push:
                _serverSocket = _context.CreatePushSocket(); break;

            case ServerType.XPub:
                _serverSocket = _context.CreateXPublisherSocket(); break;

            default:
                _serverSocket = _context.CreateResponseSocket(); break;
            }
            _serverSocket.Bind("tcp://*:" + _port);
            Task.Factory.StartNew(() =>
                                  AsyncRead(_serverSocket), TaskCreationOptions.LongRunning);
        }
Пример #15
0
        protected void CreateServer()
        {
            switch (_type)
            {
            case MQServerType.Response:
                _serverSocket = _context.CreateResponseSocket(); break;

            case MQServerType.Publisher:
                _serverSocket = _context.CreatePublisherSocket(); break;

            case MQServerType.Router:
                _serverSocket = _context.CreateRouterSocket(); break;

            case MQServerType.Stream:
                _serverSocket = _context.CreateStreamSocket(); break;

            case MQServerType.Push:
                _serverSocket = _context.CreatePushSocket(); break;

            case MQServerType.XPublisher:
                _serverSocket = _context.CreateXPublisherSocket(); break;

            default:
                _serverSocket = _context.CreateResponseSocket(); break;
            }

            _serverSocket.Bind("tcp://*:" + _port);
        }
Пример #16
0
        private void SetupPublisher()
        {
            Open(0);

            _publisherSocket = _context.CreatePublisherSocket();
            _publisherSocket.Bind(_configuration.PublisherAddress);
        }
        public void Start()
        {
            _context  = NetMQContext.Create();
            _frontend = _context.CreateRouterSocket();
            _backend  = _context.CreateRouterSocket();

            _frontend.Bind("tcp://localhost:5555"); // For Clients
            _backend.Bind("tcp://localhost:5556");  // For Workers

            _frontend.ReceiveReady += _frontEnd_ReceiveReady;
            _backend.ReceiveReady  += _backEnd_ReceiveReady;

            var heartbeatTimer = new NetMQTimer(Paranoid.HEARTBEAT_INTERVAL_MS);

            heartbeatTimer.Elapsed += heartbeatTimer_Elapsed;

            _poller = new Poller();
            _poller.AddSocket(_frontend);
            _poller.AddSocket(_backend);
            _poller.AddTimer(heartbeatTimer);

            _nextHeartbeatAt = DateTime.Now.AddMilliseconds(Paranoid.HEARTBEAT_INTERVAL_MS);

            Task.Factory.StartNew(t => Run(t), _tokenSource.Token, TaskCreationOptions.LongRunning);
            Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning);
        }
Пример #18
0
        /// <summary>
        /// Initializes a new instance of the Server class
        /// </summary>
        /// <param name="connectionString">How the server should be set up, to listen on TCP port 7954 to all incoming connections: "tcp://*:7954"</param>
        public Server(string connectionString)
        {
            serverConnectionString = connectionString;
            NetMQContext context = NetMQContext.Create();

            netMqSocket = context.CreateRouterSocket();
            netMqSocket.Bind(serverConnectionString);
        }
Пример #19
0
        /// <summary>
        /// Bind the extended <see cref="NetMQSocket"/> to the specified <paramref name="endpoint"/>.
        /// </summary>
        /// <param name="socket"> The socket that should be bound to the specified <paramref name="endpoint"/>. </param>
        /// <param name="endpoint"> The endpoint that should be bound to the <paramref name="socket"/>. </param>
        public static void Bind(this NetMQSocket socket, ISocketEndpoint endpoint)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            socket.Bind(endpoint.AsString());
        }
Пример #20
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();
            _workerPoller = new NetMQPoller();
            async void OnReceiveReady(object sender, NetMQSocketEventArgs args)
            {
                NetMQMessage receiveMessage = args.Socket.ReceiveMultipartMessage();
                string       address        = receiveMessage.Pop().ConvertToString();
                string       content        = receiveMessage.Last().ConvertToString(Encoding.UTF8);
                OwinContext  owinContext    = null;
                long         startTimestamp = Stopwatch.GetTimestamp();

                _logger.LogInformation($"Request starting tcp://{_hostingOptions.Host} {content}");
                owinContext = hostingApplication.CreateContext(content);
                try
                {
                    await hostingApplication.ProcessRequestAsync(owinContext);
                }
                catch (Exception ex)
                {
                    owinContext.Response.Error(ex.Message);
                    throw;
                }
                finally
                {
                    string sendContent = _serializer.Serialize(owinContext.Response);
                    _logger.LogInformation($"Request finished in {new TimeSpan((long)(TimestampToTicks * (Stopwatch.GetTimestamp() - startTimestamp))).TotalMilliseconds}ms {sendContent}");
                    NetMQMessage sendMessage = new NetMQMessage();
                    sendMessage.Append(address);
                    sendMessage.AppendEmptyFrame();
                    sendMessage.Append(sendContent, Encoding.UTF8);
                    args.Socket.SendMultipartMessage(sendMessage);
                    hostingApplication.DisponseContext(owinContext);
                }
            }

            foreach (var item in Enumerable.Range(0, _hostingOptions.ProcessCount))
            {
                NetMQSocket process = new DealerSocket();
                process.Connect(INPROC_SERVER_URL);
                process.ReceiveReady += OnReceiveReady;
                _workerPoller.Add(process);
            }

            _workerPoller.RunAsync();
            return(Task.CompletedTask);
        }
Пример #21
0
        protected override NetMQSocket CreateListener()
        {
            NetMQSocket listener = this.Context.CreatePullSocket();
            string      bindTo   = CreateAddress("tcp", Host, Port);

            listener.Bind(bindTo);

            return(listener);
        }
Пример #22
0
 public void DisposeImmediatly()
 {
     using (NetMQContext context = NetMQContext.Create())
     {
         using (NetMQSocket server = context.CreateDealerSocket())
         {
             server.Bind("tcp://*:5557");
         }
     }
 }
Пример #23
0
 private void InitZmq()
 {
     if (_ctx == null)
     {
         _ctx = NetMQContext.Create();
         _socket = _ctx.CreatePublisherSocket();
         var address = string.Format("{0}:{1}", _host, _port);
         _socket.Bind(address);
     }
 }
Пример #24
0
 public RequestHandlerSocket(NetMQContext context,
                             string address,
                             Func <byte[], TRequest> requestUnmarshaller,
                             Func <TReply, byte[]> replyMarshaller)
 {
     _requestUnmarshaller = requestUnmarshaller;
     _replyMarshaller     = replyMarshaller;
     _timeout             = TimeSpan.FromMilliseconds(100);
     _socket = context.CreateSocket(ZmqSocketType.Rep);
     _socket.Bind(address);
     Task.Factory.StartNew(Run, TaskCreationOptions.LongRunning);
 }
Пример #25
0
        public void Start()
        {
            SignalService.Logger.Info("Bind zeroMQ socket to address: {0}", Address);
            router = zeroMQContext.CreateSocket(ZmqSocketType.Router);
            router.Bind(Address);
            router.ReceiveReady += RouterOnReceiveReady;
            //poller = new Poller();
            //poller.AddSocket(router);

            //new Thread(() => poller.Start()).Start(); // TODO stop thread
            new Thread(PollerThread).Start();
        }
Пример #26
0
 public ZeroMQService(ILogger <ZeroMQService> logger, IOptions <ZMQOption> option)
 {
     _logger         = logger;
     this.xsubSocket = new XSubscriberSocket();
     this.xpubSocket = new XPublisherSocket();
     this.xsubSocket = new PullSocket();
     this.xpubSocket = new PushSocket();
     _option         = option.Value;
     xpubSocket.Bind(_option?.SendAddress ?? "tcp://127.0.0.1:5556");
     xsubSocket.Bind(_option?.ReceiveAddress ?? "tcp://127.0.0.1:5557");
     _proxy = new Proxy(xsubSocket, xpubSocket);
 }
Пример #27
0
    void Start()
    {
        AsyncIO.ForceDotNet.Force();

        response = new ResponseSocket();
        response.Bind("tcp://127.0.0.1:5555");

        sender = new DealerSocket();
        sender.Bind("tcp://127.0.0.1:5557");

        receiver = new DealerSocket();
        receiver.Bind("tcp://127.0.0.1:5558");
    }
Пример #28
0
        public NetMQScheduler(NetMQContext context, Poller poller = null)
        {
            m_context = context;
            if (poller == null)
            {
                m_ownPoller = true;

                m_poller = new Poller();
            }
            else
            {
                m_ownPoller = false;

                m_poller = poller;
            }

            m_clientSockets = new ConcurrentBag<NetMQSocket>();

            m_schedulerId = Interlocked.Increment(ref s_schedulerCounter);

            m_address = string.Format("{0}://scheduler-{1}", NetMQ.zmq.Address.InProcProtocol, m_schedulerId);

            m_serverSocket = context.CreatePullSocket();
            m_serverSocket.Options.Linger = TimeSpan.Zero;
            m_serverSocket.Bind(m_address);

            m_currentMessageHandler = OnMessageFirstTime;

            m_serverSocket.ReceiveReady += m_currentMessageHandler;

            m_poller.AddSocket(m_serverSocket);

            m_clientSocket = new ThreadLocal<NetMQSocket>(() =>
                    {
                        var socket = m_context.CreatePushSocket();
                        socket.Connect(m_address);

                        m_clientSockets.Add(socket);

                        return socket;
                    });

            m_schedulerThread = new ThreadLocal<bool>(() => false);

            if (m_ownPoller)
            {
                Task.Factory.StartNew(m_poller.Start, TaskCreationOptions.LongRunning);
            }
        }
Пример #29
0
        public void Bind()
        {
            context = NetMQContext.Create();

            if (socket != null)
            {
                throw new NetMQException("Attempt to set socket that was already defined. This would prevent successful dispose of the context later on (since we can no longer close all sockets).");
            }
            socket = context.CreateResponseSocket();
            socket.Options.Linger = new TimeSpan(0, 0, 0, 1);

            Trace.Assert(Protocol.ToLower().Equals("tcp"), "Only TCP is supported for now");

            socket.Bind("tcp://" + Host + ":" + Port);
        }
Пример #30
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);
        }
Пример #31
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();
                }
            }
        }
Пример #32
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]);*/
    }
Пример #34
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");
            }
        }
Пример #35
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完成");
        }
    // 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]);*/
    }
Пример #37
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();
            }
        }
Пример #38
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);
     }
 }
Пример #39
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="publisherAddress">the address that messages will be forwarded from</param>
        /// <param name="subscriberAddress">the address that messages should be sent to</param>
        /// <param name="heartbeat">the timespan at which to send HEARTBEAT messages (in milliseconds) - you can set this to zero if not needed</param>
        /// <param name="control">this socket will have messages also sent to it - you can set this to null if not needed</param>
        public ZeroMqHub(string publisherAddress, string subscriberAddress, int heartbeat = 0, NetMQSocket control = null)
        {
            _subscriberAddress = subscriberAddress;
            _publisherAddress = publisherAddress;
            var context = NetMQContext.Create();
            _subscriber = context.CreateXSubscriberSocket();
            _publisher = context.CreateXPublisherSocket();
            _control = control;

            if (heartbeat > 0)
            {
                _heartbeat = new NetMQTimer(heartbeat);
                _heartbeat.Elapsed += (s, a) => _publisher.Send("HEARTBEAT");
            }

            Name = "XPub-XSub";
            PSJobTypeName = typeof(ZeroMqHub).Name;

            _subscriber.Bind(subscriberAddress);
            _publisher.Bind(publisherAddress);
        }
Пример #40
0
        /// <summary>
        /// Create a new NetMQScheduler object within the given context, and optionally using the given poller.
        /// </summary>
        /// <param name="context">the NetMQContext to create this NetMQScheduler within</param>
        /// <param name="poller">(optional)the Poller for this Net to use</param>
        public NetMQScheduler([NotNull] NetMQContext context, [CanBeNull] Poller poller = null)
        {
            if (poller == null)
            {
                m_ownPoller = true;
                m_poller = new Poller();
            }
            else
            {
                m_ownPoller = false;
                m_poller = poller;
            }

            m_tasksQueue = new ConcurrentQueue<Task>();
            m_syncObject = new object();

            var schedulerId = Interlocked.Increment(ref s_schedulerCounter);

            var address = string.Format("{0}://scheduler-{1}", Address.InProcProtocol, schedulerId);

            m_serverSocket = context.CreatePullSocket();
            m_serverSocket.Options.Linger = TimeSpan.Zero;
            m_serverSocket.Bind(address);

            m_currentMessageHandler = OnMessageFirstTime;

            m_serverSocket.ReceiveReady += m_currentMessageHandler;

            m_poller.AddSocket(m_serverSocket);

            m_clientSocket = context.CreatePushSocket();
            m_clientSocket.Connect(address);

            m_schedulerThread = new ThreadLocal<bool>(() => false);

            if (m_ownPoller)
            {
                m_poller.PollTillCancelledNonBlocking();
            }
        }
Пример #41
0
        protected void CreateServer()
        {
            switch (_type)
            {
                case MQServerType.Response:
                    _serverSocket = _context.CreateResponseSocket(); break;
                case MQServerType.Publisher:
                    _serverSocket = _context.CreatePublisherSocket(); break;
                case MQServerType.Router:
                    _serverSocket = _context.CreateRouterSocket(); break;
                case MQServerType.Stream:
                    _serverSocket = _context.CreateStreamSocket(); break;
                case MQServerType.Push:
                    _serverSocket = _context.CreatePushSocket(); break;
                case MQServerType.XPublisher:
                    _serverSocket = _context.CreateXPublisherSocket(); break;
                default:
                    _serverSocket = _context.CreateResponseSocket(); break;
            }

            _serverSocket.Bind("tcp://*:" + _port);
            
           }
Пример #42
0
        private NetMQScheduler(Poller poller, PushSocket pushSocket, PullSocket pullSocket)
        {
            if (poller == null)
            {
                m_ownPoller = true;
                m_poller = new Poller();
            }
            else
            {
                m_ownPoller = false;
                m_poller = poller;
            }

            var address = string.Format("{0}://scheduler-{1}",
                Address.InProcProtocol,
                Interlocked.Increment(ref s_schedulerCounter));

            m_serverSocket = pullSocket;
            m_serverSocket.Options.Linger = TimeSpan.Zero;
            m_serverSocket.Bind(address);

            m_currentMessageHandler = OnMessageFirstTime;

            m_serverSocket.ReceiveReady += m_currentMessageHandler;

            m_poller.AddSocket(m_serverSocket);

            m_clientSocket = pushSocket;
            m_clientSocket.Connect(address);

            m_isSchedulerThread = new ThreadLocal<bool>(() => false);

            if (m_ownPoller)
            {
                m_poller.PollTillCancelledNonBlocking();
            }
        }
Пример #43
0
 private void InitZmq(string host, int port)
 {
     if (_ctx == null)
     {
         _ctx = NetMQContext.Create();
         _socket = _ctx.CreateResponseSocket();
         var address = string.Format("{0}:{1}", host, port);
         _socket.Bind(address);
         Log.InfoFormat(@"Context server running at: {0}", address);
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="NmqResponseQueue"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="port">The port.</param>
 internal NmqResponseQueue(NetMQContext context, int port)
 {
     socket = context.CreateResponseSocket();
     var address = string.Format("tcp://127.0.0.1:{0}", port);
     socket.Bind(address);
 }
Пример #45
0
        /// <summary>
        /// Starts the publishing and request servers.
        /// </summary>
        public void StartServer()
        {
            if (!ServerRunning)
            {
                _context = NetMQContext.Create();

                //the publisher socket
                _pubSocket = _context.CreatePublisherSocket();
                _pubSocket.Bind("tcp://*:" + PublisherPort);

                //the request socket
                _reqSocket = _context.CreateSocket(ZmqSocketType.Rep);
                _reqSocket.Bind("tcp://*:" + RequestPort);
                _reqSocket.ReceiveReady += _reqSocket_ReceiveReady;

                _poller = new Poller(new[] { _reqSocket });
                Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning);
            }
            ServerRunning = true;
        }
Пример #46
0
        /// <summary>
        /// Starts the server.
        /// </summary>
        public void StartServer()
        {
            if (_runServer) return;

            _runServer = true;
            _context = NetMQContext.Create();

            _socket = _context.CreateSocket(NetMQ.zmq.ZmqSocketType.Rep);
            _socket.Bind("tcp://*:" + _socketPort);
            _socket.ReceiveReady += _socket_ReceiveReady;
            _poller = new Poller(new[] { _socket });

            Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning);
        }
Пример #47
0
        public void Start(NetMQContext context)
        {
            this.SetUpMonitorChannel(context);
            this.SetUpAddSubscriberCountChannel(context);

            //this should work but the forwarder device appears to be broken - it does not use XSUb and XPUB sockets
            //forwarderDevice = new ForwarderDevice(context, PublishAddressServer, SubscribeAddressServer, DeviceMode.Threaded);
            //forwarderDevice.FrontendSetup.Subscribe(string.Empty);
            //forwarderDevice.Start();
            //while (!forwarderDevice.IsRunning)
            //{ }

            QueueDevce = new QueueDevice(context, PubSubControlBackAddressServer, PubSubControlFrontAddressServer, DeviceMode.Threaded);
            QueueDevce.Start();
            //while (!QueueDevce.IsRunning)
            //{
            //}

            this.Writeline("Control channel started");

            long count = 0;
            this.cancellationTokenSource = new CancellationTokenSource();
            var token = this.cancellationTokenSource.Token;
            Task.Run(() =>
            {
                using (frontend = context.CreateXSubscriberSocket())
                {
                    using (backend = context.CreateXPublisherSocket())
                    {
                        frontend.Bind(Pipe.PublishAddressServer); ////"tcp://*:5550");
                        backend.Bind(Pipe.SubscribeAddressServer); ////"tcp://*:5553");
                       // frontend.ReceiveReady += frontend_ReceiveReady;
                        frontend.ReceiveReady += new EventHandler<NetMQSocketEventArgs>(FrontendReceiveReady);
                        backend.ReceiveReady += new EventHandler<NetMQSocketEventArgs>(BackendReceiveReady);
                       // this.AddSubscriberCountChannel.ReceiveReady += new EventHandler<NetMQSocketEventArgs>(AddSubscriberCountChannelReceiveReady);
                        using (this.poller = new Poller(new NetMQSocket[] { frontend, backend, this.AddSubscriberCountChannel }))
                        {
                            Writeline("About to start polling");

                            while (true)
                            {
                                poller.Start(); // .PollOnce(); .Poll(new TimeSpan(0,0,0,0,5));
                                Writeline("polling" + count);
                                count++;
                                if (token.IsCancellationRequested)
                                {
                                    Writeline("break");
                                    break;
                                }
                            }
                        }

                        Writeline("stopped polling and exiting");
                    }
                }
            },
            token);
        }
Пример #48
0
 public void ConnectOrBindAddress(NetMQSocket socket)
 {
     var address = $"{Uri.Scheme}://{Uri.Host}:{Uri.Port}";
     socket.Bind(address);
 }
Пример #49
0
 public Broadcaster()
 {
     ctx = NetMQContext.Create();
     server = ctx.CreatePublisherSocket();
     server.Bind("tcp://127.0.0.1:5003");
 }
Пример #50
0
        /// <summary>
        /// Start the server.
        /// </summary>
        public void StartServer()
        {
            //check that it's not already running
            if (ServerRunning) return;
            _context = NetMQContext.Create();

            _routerSocket = _context.CreateSocket(NetMQ.zmq.ZmqSocketType.Router);
            _routerSocket.Bind("tcp://*:" + _listenPort);
            _routerSocket.ReceiveReady += socket_ReceiveReady;

            _poller = new Poller(new[] { _routerSocket });

            Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning);

            ServerRunning = true;
        }