예제 #1
0
        /// <summary>
        /// 断掉连接,重新连接
        /// </summary>
        void ReconnectIfDis()
        {
            ///
            /// 超时处理
            ///
            isConnected = false;
            if (reqSock != null)
            {
                reqSock.Disconnect(ConnectingAddress);
                reqSock.Close();
            }

            ConsoleEx.DebugLog("HeartBeat socket is Connecting...", ConsoleEx.RED);

            var context = Core.ZeroMQ;

            reqSock = context.CreateRequestSocket();
            reqSock.Options.SendHighWatermark    = EngCfg.HighWatermark;
            reqSock.Options.ReceiveHighWatermark = EngCfg.HighWatermark;

            //生成通讯地址和协议方式
            ConnectingAddress = ConnectAddr(typeof(HeartBeatClient));
            reqSock.Connect(ConnectingAddress);

            isConnected = true;

            RepeatTimer.Change(IntervalPeriod, Timeout.Infinite);
        }
예제 #2
0
        private void StartWorkProc()
        {
            if (null != _worker)
            {
                _worker.Close();
                _worker.Dispose();
            }

            _workProc = Task.Run(DoStart, _cancel.Token).ConfigureAwait(false);
        }
예제 #3
0
 /// <summary>
 /// 断掉连接,重新连接
 /// </summary>
 public void ReceiveTimeout()
 {
     ConsoleEx.DebugLog("Req Sock is timeout.", ConsoleEx.RED);
     ///
     /// 超时处理
     ///
     connected = false;
     if (reqSock != null)
     {
         reqSock.Disconnect(ConnectingAddress);
         reqSock.Close();
     }
     establish(Reconnected);
 }
예제 #4
0
        public T SendMessage <T>(object msg, int timeoutMs = 1000)
        {
            byte[] reply;

            socket.SendFrame(SerializationHelpers.StructureToByteArray(msg));
            var success = socket.TryReceiveFrameBytes(TimeSpan.FromMilliseconds(timeoutMs), out reply);

            if (success)
            {
                return(SerializationHelpers.ByteArrayToStructure <T>(reply));
            }

            socket.Close();
            throw new TimeoutException();
        }
예제 #5
0
    // Client thread which does not block Update()
    void NetMQClient()
    {
        AsyncIO.ForceDotNet.Force();
        NetMQContext context = null;

        context = NetMQContext.Create();

        string msg;
        var    timeout = new System.TimeSpan(0, 0, 1); //1sec

        Debug.Log("Connect to the server.");
        var requestSocket = new RequestSocket(">tcp://192.168.11.36:50020");

        requestSocket.SendFrame("SUB_PORT");
        bool is_connected = requestSocket.TryReceiveFrameString(timeout, out msg);

        while (is_connected && stop_thread_ == false)
        {
            Debug.Log("Request a message.");
            requestSocket.SendFrame("msg");
            is_connected = requestSocket.TryReceiveFrameString(timeout, out msg);
            Debug.Log("Sleep");
            Thread.Sleep(1000);
        }

        requestSocket.Close();
        Debug.Log("ContextTerminate.");
        context.Terminate();
    }
예제 #6
0
 public void Close()
 {
     lock (_locker)
     {
         _requestSocket.Close();
     }
 }
 private void DestroyRequestSocket()
 {
     if (requestSocket != null)
     {
         requestSocket.Close();
     }
 }
예제 #8
0
    void NetMQClient()
    {
        AsyncIO.ForceDotNet.Force();

        requestSocket = new RequestSocket();
        requestSocket.Connect("tcp://127.0.0.1:5555");

        while (!requestsCancelled)
        {
        }

        requestSocket.Close();
        NetMQConfig.Cleanup();

        //using (var reqSocket = new RequestSocket())
        //{
        //    reqSocket.Connect("tcp://127.0.0.1:5555");
        //    while (!requestsCancelled)
        //    {
        //        if (frame != null)
        //        {
        //            reqSocket.SendMoreFrame("F");
        //            string frameBase64 = System.Convert.ToBase64String(frame);
        //            reqSocket.SendFrame(frameBase64);

        //            var msg = reqSocket.ReceiveFrameString();
        //            print("From Server: " + msg);
        //        }
        //    }
        //    reqSocket.Close();
        //}
        //NetMQConfig.Cleanup();
    }
    private void ListenerWork()
    {
        AsyncIO.ForceDotNet.Force();
        using (var reqSocket = new RequestSocket())
        {
            string message = "";

            if (_brushStrokeIndex == "")
            {
                message = _message + "," + _picture;
            }

            else
            {
                message = _message + "," + _picture + "," + _brushStrokeIndex + ',' + _brushValues;
            }

            //reqSocket.Connect("tcp://192.168.0.6:12345");
            reqSocket.Connect("tcp://localhost:12345");
            reqSocket.SendFrame(message);

            string frameString = "";

            while (frameString == null || frameString.Equals(""))
            {
                if (!reqSocket.TryReceiveFrameString(out frameString))
                {
                }
                _messageQueue.Enqueue(frameString);
                _messageDelegate(frameString);
            }
            reqSocket.Close();
        }
        NetMQConfig.Cleanup();
    }
예제 #10
0
 /// <summary>
 /// 关闭长连接
 /// </summary>
 public void Close()
 {
     if (socket != null)
     {
         socket.Close();
     }
 }
예제 #11
0
    protected override void Run()
    {
        AsyncIO.ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet

        using (SUB = new SubscriberSocket())
            using (PUB = new PublisherSocket())
                using (REQ = new RequestSocket()) {
                    SUB.Connect("tcp://localhost:5555");
                    SUB.Subscribe("");

                    PUB.Connect("tcp://localhost:5556");

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

                    Debug.Log("Connected: Receiving Messages");

                    while (Running)
                    {
                        /*Receive continuos Slicer data*/
                        string msg = SUB.ReceiveFrameString();

                        /*Send continuos Unity data*/
                        var bytes = new byte[dataPackage.t.Length * 4];
                        System.Buffer.BlockCopy(dataPackage.t, 0, bytes, 0, bytes.Length);
                        PUB.SendFrame(bytes);

                        /*Request volume data once*/
                        if (reqestData)
                        {
                            REQ.SendFrame("volume");
                            string msg2 = REQ.ReceiveFrameString();
                            Debug.Log(msg2);

                            byte[] file = System.IO.File.ReadAllBytes(msg2);
                            Debug.Log(file.Length);

                            int     d1     = System.BitConverter.ToInt32(file, 0);
                            int     d2     = System.BitConverter.ToInt32(file, 4);
                            int     d3     = System.BitConverter.ToInt32(file, 8);
                            float[] volume = new float[d1 * d2 * d3];
                            System.Buffer.BlockCopy(file, 12, volume, 0, volume.Length * sizeof(float));

                            string s = d1 + " " + d2 + " " + d3 + " : ";
                            //for (int i = 0; i < volume.Length; ++i) s += volume[i] + " ";
                            Debug.Log(s);

                            reqestData = false;
                        }

                        /*60fps*/
                        System.Threading.Thread.Sleep(16);
                    }

                    SUB.Close();
                    PUB.Close();
                    REQ.Close();
                }
        NetMQConfig.Cleanup();
    }
예제 #12
0
 protected override void Clean()
 {
     SUB.Close();
     PUB.Close();
     REQ.Close();
     NetMQConfig.Cleanup();
     AsyncIO.ForceDotNet.Force();
 }
예제 #13
0
 void CleanupClient()
 {
     if (client != null)
     {
         client.Close();
         NetMQConfig.Cleanup();
     }
 }
예제 #14
0
        protected static ServermoduleID RegisterServermoduleByTargetType(TargetType target, ConnectionInfo connInfo)
        {
            if (null == connInfo)
            {
                throw new Exception("Does not allow null");
            }

            ServerMethod method = null;

            if (TargetType.SlaveOwnerServermodule.Equals(target)) //TODO expand
            {
                method = new RegisterSlaveOwnerServermoduleMethod()
                {
                    ConnectionInfo = connInfo
                };
            }

            //socket only used for getting the servermodule ID
            var setupSocket = new RequestSocket();

            setupSocket.Connect("tcp://" + net_mq_util.NetMqUtil.SERVER_MODULE_IP + ":" + net_mq_util.NetMqUtil.SERVER_MODULE_PORT);



            var localCallID = new Random().Next();

            if (null == method)
            {
                throw new Exception();
            }
            var encodedMethod = net_mq_encoder.NetMqEncoder.GenerateServerModuleMethodMessage(new ServermoduleID()
            {
                ID = ProtocolConstants.SERVERMODULE_ID_NOT_YET_ASSIGNED
            }, new CallID()
            {
                ID = localCallID
            }, method);

            setupSocket.SendMultipartMessage(encodedMethod);

            var response = setupSocket.ReceiveMultipartMessage();

            setupSocket.Close();

            var decodedReponse = net_mq_decoder.NetMqDecoder.DecodeResponse <ServermoduleID>(response);

            if (
                ProtocolConstants.SERVERMODULE_ID_NOT_YET_ASSIGNED.Equals(decodedReponse.Item2.Item1.ID) &&
                localCallID.Equals(decodedReponse.Item2.Item2.ID)
                )
            {
                return(decodedReponse.Item1);
            }
            else
            {
                throw new MethodFailedException("The SlaveOwner Setup method failed");
            }
        }
예제 #15
0
 // generate a message when the game shuts down or switches to another Scene
 // or switched to ExampleClass2
 void OnDestroy()
 {
     mut.WaitOne();
     Debug.Log("Destroy");
     client.SendFrame("End");
     client.Close();
     NetMQConfig.Cleanup();
     mut.ReleaseMutex();
 }
예제 #16
0
        /// <summary>
        /// Sends control request to see what APIs are available.
        /// May return null if control connection dies (automatic reconnect will follow).
        /// </summary>
        public APIStatus GetStatus(int timeoutMs = 500)
        {
            APIStatus status;

            ConnectToControlSocket();

            controlSocket.SendAsJson(new ControlRequestHeader(appName, ControlRequestCode.RequestStatus));
            var success = controlSocket.TryReceiveJson(out status, timeoutMs);

            controlSocket.Close();

            if (success)
            {
                return(status);
            }

            return(null);
        }
예제 #17
0
            public void Close()
            {
                if (requestSocket != null)
                {
                    requestSocket.Close();
                }

                IsConnected = false;
            }
예제 #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="address"></param>
        /// <param name="buf"></param>
        /// <returns></returns>
        public byte[] Send(string address, byte[] buf)
        {
            var client = new RequestSocket(">tcp://" + address);  // connect

            client.SendFrame(buf);
            byte[] result = client.ReceiveFrameBytes();
            client.Close();
            client.Dispose();
            return(result);
        }
 public void CloseSockets()
 {
     RequestSocket?.Close();
     foreach (var socketKey in SubscriptionSocketForTopic.Keys)
     {
         CloseSubscriptionSocket(socketKey);
     }
     UpdateSubscriptionSockets();
     TerminateContext();
     IsConnected = false;
 }
예제 #20
0
            public void CloseSockets()
            {
                if (requestSocket != null)
                {
                    requestSocket.Close();
                }

                TerminateContext();

                IsConnected = false;
            }
예제 #21
0
 private static bool Send(string msg, out string response)
 {
     using (var client = new RequestSocket())
     {
         client.Connect(push_server);
         client.TrySendFrame(new TimeSpan(0, 0, 3), Encoding.UTF8.GetBytes(msg));
         bool result = client.TryReceiveFrameString(new TimeSpan(0, 0, 3), Encoding.UTF8, out response);
         client.Close();
         client.Dispose();
         return(result);
     }
 }
예제 #22
0
        private void Send(byte[] str)
        {
            var address = "tcp://10.22.25.50:55688";

            //var address = "tcp://127.0.0.1:55688";
            byte[] data_1 = null;

            /*if(str == null)
             * {
             *  ZLoc.Text = "00";
             * }
             * else
             * {
             *  ZLoc.Text = Encoding.ASCII.GetString(str).ToString();
             * }*/
            using (var client = new RequestSocket(address))
            {
                var time = TimeSpan.FromMilliseconds(5000);

                /*if (str == null)
                 * {
                 *  ZLoc.Text = "00";
                 *
                 *  option = "\x00";
                 *  value = "\x00";
                 *
                 *  left_st = "\xFF";
                 *  left_nd = "\xFF";
                 *  front_pn = "\xFF";
                 *  right_st = "\xFF";
                 *  right_nd = "\xFF";
                 *  back_pn = "\xFF";
                 *
                 *  str = start_value + option + value + left_st + left_nd + front_pn + right_st +
                 *              right_nd + back_pn + end_value + end_value_2 + end_value_3;
                 * }*/

                //client.TrySendFrame(time,data_2);
                //client.TrySendMultipartBytes(time, data);
                //ZLoc.Text = Encoding.ASCII.GetString(data_1).ToString();
                //data_1 = Encoding.UTF32.GetBytes(str);
                client.TrySendFrame(time, str);


                var timeout = TimeSpan.FromSeconds(5000);
                client.TryReceiveFrameString(timeout, out string result);

                Debug.WriteLine(result);
                label4.Text = result;
                client.Close();
            }
        }
예제 #23
0
        private TimeoutException Timeout()
        {
            socket.Close();
            keepAliveTimer?.Stop();

            if (AutoRestartOnTimeout)
            {
                socket.Dispose();
                CreateSocket();
            }

            return(new TimeoutException());
        }
예제 #24
0
        /// <summary>
        /// Sends control request to see what APIs are available.
        /// May return null if control conenction dies (automatic reconnect will follow).
        /// </summary>
        public APIStatus GetStatus()
        {
            APIStatus status;

            if (controlSocket == null)
            {
                return(null);
            }

            controlSocket.SendAsJson(new ControlRequestHeader(ControlRequestCode.RequestStatus));
            var success = controlSocket.TryReceiveJson(out status, 500);

            if (success)
            {
                return(status);
            }

            // Reconnect if something goes wrong
            controlSocket.Close();
            Connect();

            return(null);
        }
예제 #25
0
파일: Network.cs 프로젝트: cxdcxd/RRS
    public void killConnect()
    {
        app_exit_res = true;

        if (res_thread != null)
        {
            res_thread.Abort();
        }

        if (request != null)
        {
            request.Close();
        }
    }
예제 #26
0
        /// <summary>
        /// 心跳
        /// </summary>
        /// <returns></returns>
        public static void ApiTest()
        {
            var request = new RequestSocket();
            var config  = StationProgram.GetConfig(station);

            try
            {
                int id = 1;
                request.Options.Identity          = RandomOperate.Generate(8).ToAsciiBytes();
                request.Options.ReconnectInterval = new TimeSpan(0, 0, 0, 0, 200);
                request.Connect(config.OutAddress);
                //for (int i = 0; i < 1024; i++)//
                {
                    Console.WriteLine("request...");
                    DateTime s = DateTime.Now;
                    request.SendFrame(api, true);
                    request.SendFrame($"{++id}", true);
                    request.SendFrame("{}", true);
                    if (!request.TrySendFrame(new TimeSpan(0, 0, 0, 3), argument))
                    {
                        Console.WriteLine("*  3");
                        return;
                    }
                    bool more = true;
                    //收完消息
                    while (more)
                    {
                        string result;
                        if (request.TryReceiveFrameString(new TimeSpan(0, 0, 0, 500), out result, out more))
                        {
                            Console.WriteLine(result);
                            continue;
                        }
                        Console.WriteLine("*  4");
                        return;
                    }
                    time += (DateTime.Now - s).TotalMilliseconds;
                    cnt++;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                request.Close();
                //tasks.Remove(Task.CurrentId.Value);
            }
        }
예제 #27
0
    protected override void Run()
    {
        ForceDotNet.Force();                  // this line is needed to prevent unity freeze after one use, not sure why yet

        using (server = new ResponseSocket()) // check if its response or request ?
        {
            server.Bind("tcp://*:1234");      //SEND

            using (client = new RequestSocket())
            {
                client.Connect("tcp://localhost:2222"); // RECIEVE


                // for (int i = 0; i < 2 && Running; i++)
                while (Running)
                {
                    // TO BE ABLE TO SEND USING SERVER SOCKET:
                    string DummyServerReceive = server.ReceiveFrameString();
                    //Debug.Log("MY DUMMY SERVER REC: " + DummyServerReceive);
                    //SENDING TO SERVER :  //SEND A VARIABLE BOOLEAN HERE
                    server.SendFrame(Mode + "," + Yindex + "," + Xindex + "," + Resign + "," + Pass + "," + HumanColor);
                    //Pass = "******";
                    //Resign = "-1";
                    //Debug.Log("SERVER IS DONE ");

                    // DUMMY SEND OF CLIENT TO RECEIVE
                    client.SendFrame("HELLOOOOOOO");

                    while (Running)
                    {
                        message = client.ReceiveFrameString(); // this returns true if it's successful

                        //Debug.Log("MESSAGE IS :" + this.message);

                        break;
                    }
                }

                client.Disconnect("tcp://localhost:2222");
                client.Close();
                client.Dispose();
            }
            server.Disconnect("tcp://*:1234");
            server.Close();
            server.Dispose();
        }

        NetMQConfig.Cleanup();
    }
예제 #28
0
    public void CloseSockets()
    {
        if (requestSocket != null && isConnected)
        {
            requestSocket.Close();
            isConnected = false;
        }

        foreach (var socketKey in subscriptionSocketForTopic.Keys)
        {
            CloseSubscriptionSocket(socketKey);
        }
        UpdateSubscriptionSockets();

        TerminateContext();
    }
예제 #29
0
    public void CloseSockets()
    {
        if (requestSocket != null && isConnected)
        {
            requestSocket.Close();
            isConnected = false;
        }

        if (subscribeSocket != null)
        {
            subscribeSocket.Close();
        }
        if (contextExists)
        {
            NetMQConfig.ContextTerminate();
        }
    }
예제 #30
0
    // ReSharper disable once InconsistentNaming
    private void NetMQClient()
    {
        AsyncIO.ForceDotNet.Force();

        requestSocket = new RequestSocket();
        // "tcp://192.168.0.104:5555"
        requestSocket.Connect("tcp://127.0.0.1:5555");

        isAvailable = true;

        while (!clientStopped)
        {
            // Debug.Log("continuing");
        }

        requestSocket.Close();
        NetMQConfig.Cleanup();
    }
예제 #31
0
파일: Program.cs 프로젝트: JayShelton/netmq
 private static void TerminateClient(RequestSocket client)
 {
     client.Disconnect(SERVER_ENDPOINT);
     client.Close();
 }
예제 #32
0
 private static void TerminateClient(RequestSocket client)
 {
     client.Disconnect(ServerEndpoint);
     client.Close();
 }