void StartListen()
    {
        // multicast receive setup
        remote_end = new IPEndPoint (IPAddress.Any, port);
        udp_client = new UdpClient (remote_end);
        udp_client.JoinMulticastGroup (group_address);

        // async callback for multicast
        udp_client.BeginReceive (new AsyncCallback (ReceiveAnnounceCallback), null);
    }
        public void Start()
        {
            Open();

            _sharedConn?.BeginReceive(OnReceiveData, _sharedConn);
            _exclusiveConn?.BeginReceive(OnReceiveData, _exclusiveConn);
        }
Exemple #3
0
        /// <summary>
        /// Handle Receive event for an UADP channel
        /// </summary>
        /// <param name="result"></param>
        private void OnReceive(IAsyncResult result)
        {
            try
            {
                // this is what had been passed into BeginReceive as the second parameter:
                UdpClient socket = result.AsyncState as UdpClient;
                // points towards whoever had sent the message:
                IPEndPoint source = new IPEndPoint(0, 0);
                // get the actual message and fill out the source:
                socket?.EndReceive(result, ref source);

                if (IsHostAddress(source.Address.ToString()))
                {
                    //signal that uadp message was received from local ip
                    m_shutdownEvent.Set();
                    return;
                }

                // schedule the next receive operation once reading is done:
                socket?.BeginReceive(new AsyncCallback(OnReceive), socket);
            }
            catch (Exception ex)
            {
                Assert.Warn(string.Format("OnReceive() failed due to the following reason: {0}", ex.Message));
            }
        }
Exemple #4
0
        private void OnReceive(IAsyncResult result)
        {
            byte[] receivedData = {};

            try {
                receivedData = UdpClient.EndReceive(result, ref _endPoint);
            } catch (Exception e) {
                Logger.Get().Warn(this, $"UDP Receive exception: {e.Message}");
            }

            // Immediately start listening for new data
            // Only do this when the client exists, we might have closed the client
            UdpClient?.BeginReceive(OnReceive, null);

            // If we did not receive at least an int of bytes, something went wrong
            if (receivedData.Length < 4)
            {
                Logger.Get().Error(this, $"Received incorrect data length: {receivedData.Length}");

                return;
            }

            List <Packet.Packet> packets;

            // Lock the leftover data array for synchronous data handling
            // This makes sure that from another asynchronous receive callback we don't
            // read/write to it in different places
            lock (_lock) {
                packets = PacketManager.HandleReceivedData(receivedData, ref _leftoverData);
            }

            _onReceive?.Invoke(packets);
        }
Exemple #5
0
        public void ReceiveCallback(IAsyncResult ar)
        {
            var endpoint = new IPEndPoint(MulticastAddress, Port);

            try
            {
                var receiveBytes = Client?.EndReceive(ar, ref endpoint);
                PacketReceived?.Invoke(this, receiveBytes);
            }
            catch (ObjectDisposedException)
            {
                if (isQuitting)
                {
                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            Console.WriteLine($"Endpoint: {endpoint}");

            Client?.BeginReceive(ReceiveCallback, null);
        }
Exemple #6
0
        static AbletonConnector()
        {
            try {
                connection = new UdpClient(1548);
            } catch {}

            connection?.BeginReceive(new AsyncCallback(Receive), connection);
        }
Exemple #7
0
        public void Start()
        {
            _disposing = false;

            Open();

            _sharedConn?.BeginReceive(OnReceiveData, _sharedConn);
            _exclusiveConn?.BeginReceive(OnReceiveData, _exclusiveConn);
        }
    public Backend(string ipAddress, int port)
    {
        // endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
        // this.EnableTimedTriggers();

        endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
        client = new UdpClient();
        client.Connect(endpoint);
        client.BeginReceive(new AsyncCallback(OnMessageRecieved), null);
    }
 public DiscoveryManager()
 {
     ActivityServices = new List<ServiceInfo>();
     DiscoveryType = DiscoveryType.WsDiscovery;
     #if ANDROID
     _messageId = Guid.NewGuid().ToString();
     _udpClient = new UdpClient(WsDiscoveryPort);
     _udpClient.JoinMulticastGroup(IPAddress.Parse(WsDiscoveryIPAddress));
     _udpClient.BeginReceive(HandleRequest, _udpClient);
     #endif
 }
Exemple #10
0
    static void Main(string[] args)
    {
        int receiverPort = 2000;
        UdpClient receiver = new UdpClient(receiverPort);

        Console.WriteLine("port: " + receiverPort);

        receiver.BeginReceive(alinandata, receiver);

        Console.ReadKey();
    }
Exemple #11
0
    public void Init(string nothing)
    {
        remoteEndPoint = new IPEndPoint(IPAddress.Parse(remoteAddress), remotePort);
        timestamps = new Dictionary<string, Timestamp>();
        receivedMsgBuffer = new StringBuilder();
        completeMsgBuffer = new List<string>();

        try
        {
            TCPBuffer = new byte[1024];

            sendingUDPClient = new UdpClient();
            sendingUDPClient.ExclusiveAddressUse = false;
            sendingUDPClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            sendingUDPClient.Connect(remoteAddress, remotePort);

            receivingUDPClient = new UdpClient();
            receivingUDPClient.ExclusiveAddressUse = false;
            receivingUDPClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            receivingUDPClient.Client.Bind((IPEndPoint)sendingUDPClient.Client.LocalEndPoint);
            receivingUDPClient.Connect(remoteAddress, remotePort);
            receivingUDPClient.BeginReceive(new AsyncCallback(OnMessageUDP), null);

            // Send initial message to register the address and port at the server
            string hello = "Hello Server";
            byte[] bytes = Encoding.UTF8.GetBytes(hello);

            try
            {
                sendingUDPClient.Send(bytes, bytes.Length);
            }
            catch (Exception err)
            {
        #if !UNITY_EDITOR
                    Application.ExternalCall(onErrorCallback, "An error occurred while sending the initial message to the server: " + err.Message);
        #else
                    UnityEngine.Debug.LogError("An error occurred while sending the initial message to the server: " + err.Message);
        #endif
            }

            TCPClient = new TcpClient();
            TCPClient.NoDelay = true;
            TCPClient.Connect(remoteEndPoint);
            TCPClient.GetStream().BeginRead(TCPBuffer, 0, 1024, new AsyncCallback(OnMessageTCP), null);
        }
        catch (Exception err)
        {
        #if !UNITY_EDITOR
                Application.ExternalCall(onErrorCallback, err.ToString());
        #else
                UnityEngine.Debug.LogError("Init(): " + err.ToString());
        #endif
        }
    }
    void RecieveCandidates()
    {
        IPEndPoint remote_end = new IPEndPoint (IPAddress.Any, startup_port);
        UdpClient udp_client = new UdpClient (remote_end);
        udp_client.JoinMulticastGroup (group_address);

        UdpState s = new UdpState();
        s.e = remote_end;
        s.u = udp_client;

        // async callback for multicast
        udp_client.BeginReceive (new AsyncCallback (ServerLookup), s);
    }
Exemple #13
0
    public static void ReceiveMessages()
    {
        // Receive a message and write it to the console.
          e = new IPEndPoint(IPAddress.Any, 19000);
          u = new UdpClient(e);

          Console.WriteLine("listening for messages");
          u.BeginReceive(new AsyncCallback(ReceiveCallback), null);

          // Do some work while we wait for a message. For this example,
          // we'll just sleep
          while (true)
          {
        Thread.Sleep(100);
          }
    }
Exemple #14
0
	static int Main (string [] args)
	{
		int port = 8001;
		UdpClient udpClient = new UdpClient (port);
		IPAddress ip = IPAddress.Parse ("224.0.0.2");
		udpClient.JoinMulticastGroup (ip, IPAddress.Any);
		udpClient.MulticastLoopback = true;
		udpClient.Ttl = 1;
		udpClient.BeginReceive (ReceiveNotification, udpClient);
		udpClient.Send (new byte [1] { 255 }, 1, new IPEndPoint (ip, port));
		System.Threading.Thread.Sleep (1000);
		udpClient.DropMulticastGroup (ip);
		if (!_receivedNotification)
			return 1;
		return 0;
	}
    public void udpRestart()
    {
        if (_udpClient != null)
        {
            _udpClient.Close();
        }

        _stringsToParse = new List<byte[]>();

        _anyIP = new IPEndPoint(IPAddress.Any, TrackerProperties.Instance.listenPort);

        _udpClient = new UdpClient(_anyIP);

        _udpClient.BeginReceive(new AsyncCallback(this.ReceiveCallback), null);

        Debug.Log("[UDPListener] Receiving in port: " + TrackerProperties.Instance.listenPort);
    }
    void Start()
    {
        foreach (PositionUpdateBehavior pub in GameObject.FindObjectsOfType<PositionUpdateBehavior>())
        {
            updateBehaviors.Add(pub);
        }

        client = new UdpClient(port);

        try
        {
            client.BeginReceive(new AsyncCallback(AcceptCallback), null);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
        }
    }
Exemple #17
0
        private void UdpReceivedCallback(IAsyncResult result)
        {
            IPEndPoint   endpoint = new IPEndPoint(0, 0);
            ITFtpCommand command  = null;

            try
            {
                byte[] data;

                lock (this)
                {
                    if (m_client == null)
                    {
                        return;
                    }

                    data = m_client.EndReceive(result, ref endpoint);
                }

                command = m_parser.Parse(data);
            }
            catch (SocketException e)
            {
                // Handle receive error
                RaiseOnError(new NetworkError(e));
            }
            catch (TFtpParserException e2)
            {
                // Handle parser error
                RaiseOnError(new NetworkError(e2));
            }

            if (command != null)
            {
                RaiseOnCommand(command, endpoint);
            }

            lock (this)
            {
                m_client?.BeginReceive(UdpReceivedCallback, null);
            }
        }
Exemple #18
0
        void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                UdpClient    u = ((UdpState)ar.AsyncState).udpClient;
                IPEndPoint   e = ((UdpState)ar.AsyncState).ipEndPoint;
                IAsyncResult r = ((UdpState)ar.AsyncState).result;

                byte[] receiveBytes = u?.EndReceive(ar, ref e);
                if (receiveBytes?.Length > 1)
                {
                    RaiseDataReceived(DeCompress(receiveBytes));
                }

                r = u?.BeginReceive(new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine($"ReceiveCallback: {e.Message}");
            }
        }
        static void Receive(IAsyncResult result)
        {
            lock (locker) {
                if (connection == null || result == null)
                {
                    return;
                }

                IPEndPoint source  = null;
                byte[]     message = connection?.EndReceive(result, ref source);

                connection?.BeginReceive(new AsyncCallback(Receive), connection);

                if (source.Address.Equals(localhost))
                {
                    if (!portMap.ContainsKey(source))
                    {
                        if (message[0] >= 242 && message[0] <= 244)
                        {
                            connection?.SendAsync(new byte[] { 244, Convert.ToByte((portMap[source] = MIDI.ConnectAbleton(244 - message[0])).Name.Substring(18)) }, 2, source);
                        }
                    }
                    else if (message[0] < 128)
                    {
                        NoteOnMessage msg = new NoteOnMessage(Channel.Channel1, (Key)message[0], message[1]);
                        portMap[source].NoteOn(null, in msg);
                    }
                    else if (message[0] == 245)
                    {
                        MIDI.Disconnect(portMap[source]);
                        portMap.Remove(source);
                    }
                    else if (message[0] == 246 && Program.Project != null)
                    {
                        Program.Project.BPM = BitConverter.ToUInt16(message, 1);
                    }
                }
            }
        }
        private void OnReceiveCallBack(IAsyncResult ar)
        {
            UdpClient  u = (UdpClient)ar.AsyncState;
            IPEndPoint e = new IPEndPoint(IPAddress.Any, 0);

            try
            {
                byte[] receiveBytes  = u.EndReceive(ar, ref e);
                string receiveString = Encoding.ASCII.GetString(receiveBytes);

                Regex exp   = new Regex("BT-SEARCH \\* HTTP/1.1\\r\\nHost: 239.192.152.143:6771\\r\\nPort: (?<port>[^@]+)\\r\\nInfohash: (?<hash>[^@]+)\\r\\n\\r\\n\\r\\n");
                Match match = exp.Match(receiveString);

                if (!match.Success)
                {
                    return;
                }

                int portcheck = Convert.ToInt32(match.Groups["port"].Value);
                if (portcheck < 0 || portcheck > 65535)
                {
                    return;
                }

                TorrentManager manager   = null;
                InfoHash       matchHash = InfoHash.FromHex(match.Groups["hash"].Value);
                for (int i = 0; manager == null && i < engine.Torrents.Count; i++)
                {
                    if (engine.Torrents [i].InfoHash == matchHash)
                    {
                        manager = engine.Torrents [i];
                    }
                }

                if (manager == null)
                {
                    return;
                }

                Uri  uri  = new Uri("tcp://" + e.Address.ToString() + ':' + match.Groups["port"].Value);
                Peer peer = new Peer("", uri, EncryptionTypes.All);

                // Add new peer to matched Torrent
                if (!manager.HasMetadata || !manager.Torrent.IsPrivate)
                {
                    ClientEngine.MainLoop.Queue(delegate {
                        int count = manager.AddPeersCore(peer);
                        manager.RaisePeersFound(new LocalPeersAdded(manager, count, 1));
                    });
                }
            }
            catch
            {
                // Failed to receive data, ignore
            }
            finally
            {
                try
                {
                    u.BeginReceive(OnReceiveCallBack, ar.AsyncState);
                }
                catch
                {
                    // It's closed
                }
            }
        }
Exemple #21
0
        void DiscoveryCallback(IAsyncResult ar)
        {
            UdpClient  udpClient = (UdpClient)((ShepherdUdpState)(ar.AsyncState)).Client;
            IPEndPoint ip        = (IPEndPoint)((ShepherdUdpState)(ar.AsyncState)).Ip;

            XMLStream inputXMLStream = new XMLStream();

            XElement xmlDescription;
            string   herdAgentXMLDescription;

            try
            {
                Byte[] receiveBytes = udpClient.EndReceive(ar, ref ip);
                {
                    herdAgentXMLDescription = Encoding.ASCII.GetString(receiveBytes);
                    if (herdAgentXMLDescription.IndexOf('<') == 0)
                    {
                        xmlDescription = XElement.Parse(herdAgentXMLDescription);
                        HerdAgentInfo herdAgentInfo = new HerdAgentInfo();
                        herdAgentInfo.Parse(xmlDescription);
                        //we copy the ip address into the properties
                        herdAgentInfo.ipAddress = ip;
                        //we update the ack time
                        DateTime now = DateTime.Now;
                        herdAgentInfo.lastACK = now;
                        bool agentAddedToList = false;
                        lock (m_listLock)
                        {
                            if (!m_herdAgentList.ContainsKey(herdAgentInfo.ProcessorId))
                            {
                                m_herdAgentList[herdAgentInfo.IpAddressString] = herdAgentInfo; //We have to use the ip address until ProcessorId is a GUID on all deployed agents
                                agentAddedToList = true;
                            }
                        }
                        if (agentAddedToList)
                        {
                            //check how much time ago the agent list was updated
                            double lastUpdateElapsedTime = (now - m_lastHerdAgentListUpdate).TotalSeconds;
                            //notify, if we have to, that the agent list has probably changed
                            if (lastUpdateElapsedTime > m_herdAgentListUpdateTime)
                            {
                                m_lastHerdAgentListUpdate = now;
                            }
                            m_notifyAgentListChanged?.Invoke(herdAgentInfo);
                        }
                    }
                }

                udpClient.BeginReceive(new AsyncCallback(DiscoveryCallback), ar.AsyncState);
            }
            catch (TaskCanceledException ex)
            {
                LogMessage("Task canceled exception in Shepherd");
                LogMessage(ex.ToString());
            }
            catch (Exception ex)
            {
                LogMessage("Exception in discovery callback function");
                LogMessage(ex.StackTrace);
            }
        }
Exemple #22
0
            // Wiresharkの表示を参考にした
            public static XmlDocument Query(IPEndPoint ip, int millisecs)
            {
                using (UdpClient client = new UdpClient(ip.AddressFamily)) {
                    client.Connect(ip);

                    Random rand = new Random();
                    ushort seed = (ushort)rand.Next();
                    {
                        MemoryStream os = new MemoryStream();
                        BEW          wr = new BEW(os);
                        wr.Write(seed);
                        wr.Write((ushort)0); //Flags: 0x0000 (Name query)
                        wr.Write((ushort)1); //Questions: 1
                        wr.Write((ushort)0); //Answer RRs: 0
                        wr.Write((ushort)0); //Authority RRs: 0
                        wr.Write((ushort)0); //Additional RRs: 0

                        wr.Write((byte)32);
                        wr.Write(Encoding.ASCII.GetBytes("CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
                        wr.Write((byte)0);

                        wr.Write((ushort)0x21); //Type: NBSTAT
                        wr.Write((ushort)0x01); //Class: IN

                        byte[] bin = os.ToArray();
                        if (client.Send(bin, bin.Length) != bin.Length)
                        {
                            throw new EndOfStreamException();
                        }
                    }

                    {
                        XmlDocument xmlo   = new XmlDocument();
                        XmlElement  elroot = xmlo.CreateElement("wins");
                        xmlo.AppendChild(elroot);
                        XmlElement elres = xmlo.CreateElement("response");
                        elroot.AppendChild(elres);

                        byte[] bin;
                        {
                            IPEndPoint   ipr = new IPEndPoint(0, 0);
                            IAsyncResult ar  = client.BeginReceive(CbReceived, null);
                            if (false == ar.AsyncWaitHandle.WaitOne(millisecs, false))
                            {
                                client.Close();
                            }
                            bin = client.EndReceive(ar, ref ipr);
                        }
                        MemoryStream si    = new MemoryStream(bin, false);
                        BER          br    = new BER(si);
                        ushort       rseed = br.ReadUInt16();
                        if (rseed != seed)
                        {
                            throw new InvalidDataException();
                        }
                        ushort fl = br.ReadUInt16();
                        if (0 == (fl & 0x8000) || 0 != (fl & 15))
                        {
                            throw new InvalidDataException();
                        }

                        {
                            int cnt = br.ReadUInt16();
                            for (int x = 0; x < cnt;)
                            {
                                throw new NotSupportedException();
                            }
                        }

                        int[] acnt = new int[3];
                        acnt[0] = br.ReadUInt16();
                        acnt[1] = br.ReadUInt16();
                        acnt[2] = br.ReadUInt16();

                        for (int t = 0; t < 3; t++)
                        {
                            XmlElement elrrs = null;
                            if (t == 0)
                            {
                                elrrs = xmlo.CreateElement("answer-rrs");
                            }
                            if (t == 1)
                            {
                                elrrs = xmlo.CreateElement("authority-rrs");
                            }
                            if (t == 2)
                            {
                                elrrs = xmlo.CreateElement("additional-rrs");
                            }
                            elres.AppendChild(elrrs);

                            for (int x = 0; x < acnt[t]; x++)
                            {
                                XmlElement ela = xmlo.CreateElement("answer");
                                elrrs.AppendChild(ela);

                                byte   cb   = br.ReadByte();
                                byte[] name = br.ReadBytes(cb);
                                ela.SetAttribute("raw-name", Encoding.ASCII.GetString(name));
                                byte nodeType = br.ReadByte();
                                ela.SetAttribute("node-type", nodeType.ToString("x2"));

                                int atype = br.ReadUInt16();
                                if (atype != 0x21)
                                {
                                    throw new NotSupportedException();
                                }

                                int aclass = br.ReadUInt16();
                                if (aclass != 1)
                                {
                                    throw new NotSupportedException();
                                }

                                uint attl = br.ReadUInt32();
                                ela.SetAttribute("ttl", attl.ToString());

                                br.ReadUInt16();

                                byte aNamecnt = br.ReadByte();
                                for (int a = 0; a < aNamecnt; a++)
                                {
                                    String aname = Encoding.Default.GetString(br.ReadBytes(15));
                                    byte   anty  = br.ReadByte();
                                    int    afl   = br.ReadUInt16();

                                    XmlElement elan = xmlo.CreateElement("name");
                                    ela.AppendChild(elan);
                                    elan.SetAttribute("name", aname);
                                    elan.SetAttribute("name-type", anty.ToString("x2"));
                                    elan.SetAttribute("flags", afl.ToString("x4"));
                                }

                                byte[] mac = br.ReadBytes(6);
                                ela.SetAttribute("unit-id", String.Format("{0:x2}:{1:x2}:{2:x2}:{3:x3}:{4:x2}:{5:x2}"
                                                                          , mac[0]
                                                                          , mac[1]
                                                                          , mac[2]
                                                                          , mac[3]
                                                                          , mac[4]
                                                                          , mac[5]
                                                                          ));
                            }
                        }

                        return(xmlo);
                    }
                }
            }
    /********************/
    /****** CLIENT ******/
    /********************/
    public void ListenServer()
    {
        // open a listening port on a random port
        // to receive a response back from server
        // using 0 doesn't seem to work reliably
        // so we'll just do it ourselves

        int myPort = UnityEngine.Random.Range(15001,16000);

        IPEndPoint ep1 = new IPEndPoint(IPAddress.Any, myPort);
        UdpClient uc1 = new UdpClient(ep1);
        UdpState us1 = new UdpState();
        us1.e = ep1;
        us1.u = uc1;
        uc1.BeginReceive(new AsyncCallback(ListenServerCallback), us1);
        broadcastClient = uc1;
        broadcastEndPoint = ep1;

        Debug.Log("Broadcast listener opened on port " + broadcastEndPoint.Port.ToString());
    }
Exemple #24
0
 public void Start()
 {
     connection.BeginReceive(ReceiveDatagram, null);
 }
Exemple #25
0
 private void receiveData()
 {
     udpClient.BeginReceive(new AsyncCallback(dataReady), udp_ep);
 }
    //specific to LAN
    private void ListenForClients(int _ListenPort)
    {
        System.Diagnostics.Debug.Assert(m_BroadcastListeningClientLAN == null);

        // open a listening port on known port
        // to listen for any clients

        IPEndPoint ep1 = new IPEndPoint(IPAddress.Any, _ListenPort);
        UdpClient uc1 = new UdpClient(ep1);
        UdpClientState ucs1 = new UdpClientState(ep1, uc1);

        uc1.BeginReceive(new System.AsyncCallback(ListenForClientsCallback), ucs1);

        m_BroadcastListeningClientLAN = ucs1;

        Debug.Log("Server listening for clients on port: " + _ListenPort);
    }
Exemple #27
0
        private static void listenerThreadProc()
        {
            staticLogMessage(new MessageEvent("Network Clock listener thread is alive", 1, MessageEvent.MessageTypes.Log, MessageEvent.MessageCategories.Networking));


            while (true)
            {
                // Wait for a datagram from the udpClient.
                // This makes use of a temporary local reference to udpClient so that we can be sure
                // that even if the static udpClient member is changed when we don't hold the static lock
                // we will at least run the callback on the correct instance of udpClient.
                // (I didn't want to lock the receive callback on staticLockObj, because the callback may
                // take arbitrarily long to return, and I don't want to be locked out of other static activities like
                // shutting down the listener.

                System.Net.IPEndPoint remoteEnd = null;
                IAsyncResult          result;
                byte[]    received;
                UdpClient udpClientNonstatic;
                lock (staticLockObj)
                {
                    udpClientNonstatic = udpClient;
                    result             = udpClient.BeginReceive(null, null);
                }
                received = udpClientNonstatic.EndReceive(result, ref remoteEnd);

                if (received.Length != NetworkClockDatagram.datagramByteLength)
                {
                    staticLogMessage(new MessageEvent("Received wrong sized (" + received.Length + ") datagram. Dropping.", 1, MessageEvent.MessageTypes.Error, MessageEvent.MessageCategories.Networking));
                    continue;
                }

                NetworkClockDatagram ndgram = new NetworkClockDatagram(received);

#if DEBUG
                staticLogMessage(new MessageEvent("Received network clock datagram " + ndgram.ToString(), 2, MessageEvent.MessageTypes.Debug, MessageEvent.MessageCategories.Networking));
#endif
                if (ndgram.DatagramCount != lastNGramID + 1)
                {
                    staticLogMessage(new MessageEvent("Warning! Received network clock datagram #" + ndgram.DatagramCount + ", expected #" + (lastNGramID + 1) + ".", 0, MessageEvent.MessageTypes.Warning, MessageEvent.MessageCategories.Networking));
                }
                lastNGramID = ndgram.DatagramCount;

                NetworkClockProvider pr = null;

                // Pull designated provider out of provider's dictionary (locked on staticLockObj since
                // we are accessing static providers dictionary)
                // Will leave pr as null if no such ClockID listener exists.
                // Will throw an exception if clockID does exist, but listener is null.
                lock (staticLockObj)
                {
                    if (providers.ContainsKey(ndgram.ClockID))
                    {
                        pr = providers[ndgram.ClockID];
                        if (pr == null)
                        {
                            throw new SoftwareClockProviderException("Unexpected null network clock provider.");
                        }
                    }
                }

                // If provider does exist, (is not null), relay to it the latest
                // clock message
                if (pr != null)
                {
                    // Thread lock on pr object
                    lock (pr.instanceLockObj)
                    {
                        if (pr.isRunning)
                        {
                            if (!pr.receivedFirstClock)
                            {
                                staticLogMessage(new MessageEvent("Received first clock datagram for clockID " + Shared.clockIDToString(pr.clockID),
                                                                  0, MessageEvent.MessageTypes.Routine, MessageEvent.MessageCategories.SoftwareClock));
                                pr.receivedFirstClock = true;
                            }
                            pr.reachTime(ndgram.ElaspedTime);
                        }
                    }
                }
            }
        }
Exemple #28
0
    // Actually builds, sends, sets the received bytes and returns the whole packet
    private EDNSPacket SendUdpNetworkPacket(string sDNSIP, string sIPToResolve, int nPort, byte bType, bool bEDNS, byte[] bMachine_ID)
    {
        // Create empty EDNS packet
        EDNSPacket Packet = new EDNSPacket();

        try
        {
            IPEndPoint Endpoint = new IPEndPoint(IPAddress.Parse(sDNSIP), nPort);

            // Send the current machine_id host
            if (bEDNS)
                Packet.CreateEDNSPacketMachineID(sIPToResolve, bType, bMachine_ID);
            else
                Packet.CreateDNSPacket(sIPToResolve, bType);

            if (Packet.GetPacketLen() > 0)
            {
                // Create a udp client to send the packet
                UdpClient udpGo = new UdpClient();
                udpGo.Client.SendTimeout = 2000;
                udpGo.Client.ReceiveTimeout = 2000;
                udpGo.Send(Packet.GetPacket(), Packet.GetPacket().Length, Endpoint);

                //IPEndPoint object will allow us to read datagrams sent from any source.
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

                // Launch Asynchronous
                IAsyncResult iarResult = udpGo.BeginReceive(null, null);

                // Wait until complete
                bool bKill = false;
                DateTime dtTimeStart = DateTime.Now;
                while (iarResult.IsCompleted == false)
                {
                    // Sleep instead of cycling
                    System.Threading.Thread.Sleep(100);

                    // Watchdog, if doesn't return in 5 seconds get out
                    if (dtTimeStart.AddSeconds(5) < DateTime.Now)
                    {
                        bKill = true;
                        break;
                    }
                }

                // This can hang when not happy about a broken connection
                if (bKill)
                    udpGo.Close();
                else
                    Packet.SetReceivePacket(udpGo.EndReceive(iarResult, ref RemoteIpEndPoint));
            }
        }
        catch (Exception Ex)
        {
            // TODO: Log an exception?
        }

        // Always just return packet
        return Packet;
    }
 public override void Start()
 {
     udpClient.BeginReceive(EndReceive, null);
     running = true;
 }
Exemple #30
0
        public static IPAddress GetPublicIPAddress(string stunServer)
        {
            try
            {
                logger.LogDebug("STUNClient attempting to determine public IP from " + stunServer + ".");

                using (UdpClient udpClient = new UdpClient(stunServer, DEFAULT_STUN_PORT))
                {
                    STUNMessage initMessage      = new STUNMessage(STUNMessageTypesEnum.BindingRequest);
                    byte[]      stunMessageBytes = initMessage.ToByteBuffer();
                    udpClient.Send(stunMessageBytes, stunMessageBytes.Length);

                    IPAddress        publicIPAddress = null;
                    ManualResetEvent gotResponseMRE  = new ManualResetEvent(false);

                    udpClient.BeginReceive((ar) =>
                    {
                        try
                        {
                            IPEndPoint stunResponseEndPoint = null;
                            byte[] stunResponseBuffer       = udpClient.EndReceive(ar, ref stunResponseEndPoint);

                            if (stunResponseBuffer != null && stunResponseBuffer.Length > 0)
                            {
                                logger.LogDebug("STUNClient Response to initial STUN message received from " + stunResponseEndPoint + ".");
                                STUNMessage stunResponse = STUNMessage.ParseSTUNMessage(stunResponseBuffer, stunResponseBuffer.Length);

                                if (stunResponse.Attributes.Count > 0)
                                {
                                    foreach (STUNAttribute stunAttribute in stunResponse.Attributes)
                                    {
                                        if (stunAttribute.AttributeType == STUNAttributeTypesEnum.MappedAddress)
                                        {
                                            publicIPAddress = ((STUNAddressAttribute)stunAttribute).Address;
                                            logger.LogDebug("STUNClient Public IP=" + publicIPAddress.ToString() + ".");
                                        }
                                    }
                                }
                            }

                            gotResponseMRE.Set();
                        }
                        catch (Exception recvExcp)
                        {
                            logger.LogWarning("Exception STUNClient Receive. " + recvExcp.Message);
                        }
                    }, null);

                    if (gotResponseMRE.WaitOne(STUN_SERVER_RESPONSE_TIMEOUT * 1000))
                    {
                        return(publicIPAddress);
                    }
                    else
                    {
                        logger.LogWarning("STUNClient server response timedout after " + STUN_SERVER_RESPONSE_TIMEOUT + "s.");
                        return(null);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception STUNClient GetPublicIPAddress. " + excp.Message);
                return(null);
                //throw;
            }
        }
    private void ListenForServer(int _ListenPort)
    {
        System.Diagnostics.Debug.Assert(m_AdvertisingListeningClientLAN == null);

        // open a listening port on a random port
        // to receive a response back from server
        // using 0 doesn't seem to work reliably
        // so we'll just do it ourselves

        IPEndPoint ep1 = new IPEndPoint(IPAddress.Any, _ListenPort);
        UdpClient uc1 = new UdpClient(ep1);
        UdpClientState ucs1 = new UdpClientState(ep1, uc1);
        uc1.BeginReceive(new System.AsyncCallback(ListenForServerCallback), ucs1);

        m_AdvertisingListeningClientLAN = ucs1;

        Debug.Log("Finder advertising listener opened on port " + _ListenPort);
    }
Exemple #32
0
        /// <summary>
        /// Begins the UDP MITM. RemotePort must be set before calling this
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync()
        {
            // Client to send data to the server
            UdpClient sender = new UdpClient();

            // Endpoint representing the local port
            var endpoint = new IPEndPoint(IPAddress.Any, LocalPort);

            try
            {
                // Local function called when data is received
                void requestCallback(IAsyncResult ar)
                {
                    try
                    {
                        // Complete the receive and get the bytes
                        var bytes = m_listener.EndReceive(ar, ref endpoint);

                        // Send the bytes to the server
                        if (RemotePort != 0)
                        {
                            InstanceAdded = true;

                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                ProxyUiWindow.SendBytesToUi(m_connectionInstance, new CommPacket
                                {
                                    Data         = bytes,
                                    Direction    = CommPacketDirection.ClientToServer,
                                    Id           = Guid.NewGuid(),
                                    Instance     = m_connectionInstance,
                                    ParentPacket = null,
                                    Header       = "UDP data",
                                });
                            });

                            if (sender.Send(bytes, bytes.Length, RemoteHost, RemotePort) != bytes.Length)
                            {
                                throw new Exception("UDP send failed");
                            }
                        }

                        // Listen for more bytes
                        m_listener.BeginReceive(requestCallback, null);
                    }
                    catch (Exception ex)
                    {
                        // Terminate the port on failure
                        m_failureSource.TrySetException(ex);
                    }
                }

                // Perform the first listen
                m_listener.BeginReceive(requestCallback, null);
            }
            catch (Exception ex)
            {
                // Terminate the port on failure
                m_failureSource.TrySetException(ex);
            }

            try
            {
                // Wait until failure or termination
                await m_failureSource.Task;
            }
            catch { }
        }
    void StartGameClient()
    {
        // multicast receive setup
        IPEndPoint remote_end = new IPEndPoint (IPAddress.Any, startup_port);
        udp_client = new UdpClient (remote_end);
        udp_client.JoinMulticastGroup (group_address);

        // async callback for multicast
        udp_client.BeginReceive (new AsyncCallback (ServerLookup), null);

        StartCoroutine(MakeConnection ());
    }
Exemple #34
0
    // async callback for reading packets sent using udp
    private void RecievingDatagramCallback(IAsyncResult asyncResult)
    {
        //queue the async results
        // if so, start listen for new data
        if (_recievingUdpDatagrams)
        {
            _UdpListener.BeginReceive(new AsyncCallback(RecievingDatagramCallback),
                                      _UdpListener);
        }

        // retriving the client
        UdpClient client = (UdpClient)asyncResult.AsyncState;
        // creating the endPoint
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, _playerUdpListenPort);

        // save the data
        byte[] recievedData = client.EndReceive(asyncResult, ref endPoint);
        //decoding the byte to a string
        string recievedJsonString = Encoding.ASCII.GetString(recievedData);
        //save the data as a packet
        Packet recievedUdpPacket = JsonConvert.DeserializeObject <Packet>(recievedJsonString);

        // treat the reaceved data
        // if is a packet for player position
        if (recievedUdpPacket.PacketType == PacketType.PlayerPosition)
        {
            // if is a packet of movement
            // check if the packet is to this player
            // on udp connection player can only recieve packets for the mov of the other player
            // this check for all the players connected because the udp packet can reatch the client before the tcp one
            if (recievedUdpPacket.PlayerGUID == _opponentPlayer.Id &&
                _spawnedPlayers.ContainsKey(_opponentPlayer.Id))
            {
                // check if this is the newer packet
                if (recievedUdpPacket.GetSendStamp > _player.LastPacketStamp)
                {
                    // add to queue
                    _asyncActions.Enqueue(() =>
                    {
                        // if soo, add this packet to list
                        _player.PlayerPackets.Add(recievedUdpPacket);
                        // add the stamp
                        _player.LastPacketStamp = recievedUdpPacket.GetSendStamp;

                        // call method to player the player at the recieved pos
                        // set transform recieves xand y , and rotation y
                        _spawnedPlayers[_opponentPlayer.Id].
                        SetTransform(recievedUdpPacket.PlayerPosition.X,
                                     recievedUdpPacket.PlayerPosition.Y,
                                     recievedUdpPacket.ObjRotation.Y);
                    });
                }
            }
        }
        // if is a packet for obj Update
        else if (recievedUdpPacket.PacketType == PacketType.SetObjPosition)
        {
            // check if the obj is spawned
            if (_inGameCutlery != null)
            {
                // confirm if is the latest packet recieved
                if (recievedUdpPacket.GetSendStamp > _player.LastPacketStamp)
                {
                    // add to async queue
                    _asyncActions.Enqueue(() =>
                    {
                        // add this packet to the player packets
                        _player.PlayerPackets.Add(recievedUdpPacket);
                        // update the last packet stamp
                        _player.LastPacketStamp = recievedUdpPacket.GetSendStamp;

                        // update the transform of the obj
                        _inGameCutlery.transform.position =
                            new Vector3(recievedUdpPacket.ObjPosition.X,
                                        recievedUdpPacket.ObjPosition.Y, 0f);

                        // update the position
                        _inGameCutlery.transform.rotation =
                            Quaternion.Euler(0f, 0f, recievedUdpPacket.ObjRotation.Y);
                    });
                }
            }
        }
    }
Exemple #35
0
 /// <summary>
 /// This method begins the process of listening to all messages sent on the router.
 /// </summary>
 public void StartReceivingIP()
 {
     SetInstruction (searchInstructions);
     try {
         if (receiver == null) {
             receiver = new UdpClient (NaviMobileManager.RemotePort);
             receiver.BeginReceive (new AsyncCallback (ReceiveData), null);
         }
     } catch (SocketException e) {
         Debug.Log (e.Message);
     }
 }
Exemple #36
0
        public static bool IsPortOpen(string host, int port, int timeout = 20000, int retry = 1, bool isUdp = false)
        {
            var retryCount = 0;

            while (retryCount < retry)
            {
                // Logical delay without blocking the current thread.
                if (retryCount > 0)
                {
                    Task.Delay(timeout).Wait();
                }
                if (isUdp)
                {
                    // UDP is connectionless by design, therefore method below is not 100 % reliable.
                    // Firewall and network setups might influence the result.
                    var udp = new UdpClient();
                    try
                    {
                        var result  = udp.BeginSend(new byte[1], 1, host, port, null, null);
                        var success = result.AsyncWaitHandle.WaitOne(timeout);
                        if (success)
                        {
                            udp.BeginReceive(null, null);
                            udp.EndSend(result);

                            var result2  = udp.BeginReceive(null, null);
                            var success2 = result.AsyncWaitHandle.WaitOne(timeout);
                            if (success2)
                            {
                                IPEndPoint remoteEP = null;
                                udp.EndReceive(result2, ref remoteEP);
                                return(true);
                            }
                        }
                    }
                    catch (SocketException udpEx)
                    {
                        // If port was forcibly closed (WSAECONNRESET) then...
                        if (udpEx.ErrorCode == 10054)
                        {
                            return(false);
                        }
                    }
                    finally
                    {
                        udp.Close();
                        retryCount++;
                    }
                    // Answer or timeout means that port is open.
                    return(true);
                }
                else
                {
                    var tcp = new TcpClient();
                    try
                    {
                        var result  = tcp.BeginConnect(host, port, null, null);
                        var success = result.AsyncWaitHandle.WaitOne(timeout);
                        if (success)
                        {
                            tcp.EndConnect(result);
                            return(true);
                        }
                    }
                    catch { }
                    finally
                    {
                        tcp.Close();
                        retryCount++;
                    }
                }
            }
            return(false);
        }
Exemple #37
0
 /// <summary>
 /// 构建KCP客户端
 /// </summary>
 /// <param name="conv">会话id</param>
 /// <param name="port">本地端口</param>
 public KClient(UInt32 conv, int port) : base()
 {
     this.conv = conv;
     client    = new UdpClient(new IPEndPoint(IPAddress.Any, port));
     client.BeginReceive(OnRecive, null);
 }
Exemple #38
0
 public XyzUdpClient(IPAddress address, int port)
 {
     client = new UdpClient();
     this.Bind(address, port);
     client.BeginReceive(DataReceived, client);
 }
Exemple #39
0
 private void ReceiveMessages()
 {
     receiveUdpClient = new UdpClient(clientObj.ClientPort);
     receiveUdpClient.BeginReceive(new AsyncCallback(asyncCallbackReply), null);
 }
 /// <summary>
 /// Start slave listening for requests.
 /// </summary>
 public override void Listen()
 {
     _log.Debug("Start Modbus Udp Server.");
     _client.BeginReceive(ReceiveRequestCompleted, this);
 }
Exemple #41
0
 /// <summary>
 /// Asynchronously listens on the given client for a single packet.
 /// </summary>
 public static void Receive(UdpClient Client, ReceiveRawPacketHandler OnReceive)
 {
     // Good job Microsoft, for making this so easy O_O
     while (true)
     {
         try
         {
             Client.BeginReceive(delegate(IAsyncResult ar)
             {
                 lock (Client)
                 {
                     IPEndPoint end = new IPEndPoint(IPAddress.Any, 0);
                     byte[] data;
                     try
                     {
                         data = Client.EndReceive(ar, ref end);
                         OnReceive(end, data);
                     }
                     catch (SocketException se)
                     {
                         if (se.SocketErrorCode == SocketError.Shutdown)
                         {
                             return;
                         }
                         if (_CanIgnore(se))
                         {
                             Receive(Client, OnReceive);
                         }
                         else
                         {
                             throw se;
                         }
                     }
                     catch (ObjectDisposedException)
                     {
                         return;
                     }
                 }
             }, null);
             return;
         }
         catch (SocketException se)
         {
             if (!_CanIgnore(se))
             {
                 throw se;
             }
         }
         catch (ObjectDisposedException)
         {
             return;
         }
     }
 }
    /********************/
    /****** SERVER ******/
    /********************/
    public void ListenForClients(string g)
    {
        // open a listening port on known port 15000
        // to listen for any clients

        IPEndPoint ep1 = new IPEndPoint(IPAddress.Any, 15000);
        UdpClient uc1 = new UdpClient(ep1);
        UdpState us1 = new UdpState();
        us1.e = ep1;
        us1.u = uc1;
        uc1.BeginReceive(new AsyncCallback(ListenForClientsCallback), us1);

        multiGameName = g;

        waitingResponse = true;

        Debug.Log("Server listening port opened");
    }
Exemple #43
0
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        public async Task Start(IPEndPoint endpoint)
        {
            await Task.Yield();

            TaskCompletionSource <object> tcs = new TaskCompletionSource <object>();

            if (_run)
            {
                try
                {
                    _udp = new UdpClient(endpoint);

                    //判断如果关闭不重试
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        _udp.Client.IOControl(SIO_UDP_CONNRESET, new byte[4], new byte[4]);
                    }
                }
                catch (SocketException e)
                {
                    OnError(e);
                    return;
                }
            }

            AsyncCallback receiveCallback = null;

            receiveCallback = result =>
            {
                byte[] data;

                try
                {
                    IPEndPoint remote = new IPEndPoint(0, 0);
                    data = _udp.EndReceive(result, ref remote);
                    HandleRequest(data, remote);
                }
                catch (ObjectDisposedException)
                {
                    _run = false;
                }
                catch (SocketException e)
                {
                    OnError(e);
                }

                if (_run)
                {
                    _udp.BeginReceive(receiveCallback, null);
                }

                else
                {
                    tcs.SetResult(null);
                }
            };

            _udp.BeginReceive(receiveCallback, null);

            OnEvent(OnListening, EventArgs.Empty);

            await tcs.Task;
        }
Exemple #44
0
        static void Receive(IAsyncResult result)
        {
            lock (locker) {
                if (connection == null || result == null)
                {
                    return;
                }

                IPEndPoint source  = null;
                byte[]     message = connection?.EndReceive(result, ref source);

                connection?.BeginReceive(new AsyncCallback(Receive), connection);

                if (!source.Address.Equals(localhost))
                {
                    return;
                }

                if (!portMap.ContainsKey(source))
                {
                    if (message[0] == 247)
                    {
                        App.Args = new string[] { Encoding.UTF8.GetString(message.Skip(1).ToArray()) };

                        if (handlingFileOpen)
                        {
                            return;
                        }
                        handlingFileOpen = true;

                        Dispatcher.UIThread.InvokeAsync(async() => {
                            if (Program.Project == null)
                            {
                                App.Windows.OfType <SplashWindow>().First().ReadFile(App.Args[0]);
                            }
                            else
                            {
                                await Program.Project.AskClose();
                            }

                            App.Args         = null;
                            handlingFileOpen = false;
                        });
                    }
                    else if (message[0] >= 242 && message[0] <= 244)
                    {
                        connection?.SendAsync(new byte[] { 244, Convert.ToByte((portMap[source] = MIDI.ConnectAbleton(244 - message[0])).Name.Substring(18)) }, 2, source);
                    }
                }
                else if (message[0] < 128)
                {
                    portMap[source].HandleNote(message[0], message[1]);
                }

                else if (message[0] == 245)
                {
                    MIDI.Disconnect(portMap[source]);
                    portMap.Remove(source);
                }
                else if (message[0] == 246 && Program.Project != null)
                {
                    Program.Project.BPM = BitConverter.ToUInt16(message, 1);
                }
            }
        }
Exemple #45
0
        private void ProcessDgram(IAsyncResult res)
        {
            try
            {
                byte[] recieved = _client.EndReceive(res, ref _hostEndPoint);

                if (DebugEnabled)
                {
                    Debug.Log("[SocketManager] recieved: " + Encoding.UTF8.GetString(recieved));
                }

                string packet = Encoding.UTF8.GetString(recieved);

                string packetType = packet.Substring(0, 4);
                string packetData = packet.Remove(0, 4);

                switch (packetType)
                {
                case "EVNT":
                    lock (_socketEventQueue) {
                        ISocketEvent socketEvent = new StringUnitySocketEvent(onEventReceived, packetData);
                        _socketEventQueue.Enqueue(socketEvent);
                    }
                    break;

                case "UDAT":
                    lock (_socketEventQueue) {
                        SessionDataUpdateEventInfo info = JsonUtility.FromJson <SessionDataUpdateEventInfo>(packetData);
                        ISocketEvent socketEvent        = new SessionDataUpdateUnitySocketEvent(onSessionDataUpdateReceived, info);
                        _socketEventQueue.Enqueue(socketEvent);
                    }
                    break;

                case "GDAT":
                    lock (_socketEventQueue) {
                        ISocketEvent socketEvent = new StringUnitySocketEvent(onSessionDataGetReceived, packetData);
                        _socketEventQueue.Enqueue(socketEvent);
                    }
                    break;

                case "JRES":
                    lock (_socketEventQueue) {
                        ISocketEvent socketEvent = new ActionSocketEvent(OnConnected);
                        _socketEventQueue.Enqueue(socketEvent);
                    }
                    break;

                case "QUIT":
                    lock (_socketEventQueue) {
                        ISocketEvent socketEvent = new ActionSocketEvent(OnDisconnected);
                        _socketEventQueue.Enqueue(socketEvent);
                    }
                    break;

                default:
                    Debug.Log("[SocketManager] Recieved Unknown Message: /n" + packet);
                    break;
                }
                _client.BeginReceive(new AsyncCallback(ProcessDgram), _client);
            }
            catch (Exception ex)
            {
                lock (_socketEventQueue) {
                    ISocketEvent socketEvent = new ExceptionUnitySocketEvent(onSocketException, ex);
                    _socketEventQueue.Enqueue(socketEvent);
                }
            }
        }
 private void Listen()
 {
     _ar = _udpClient.BeginReceive(OnReceive, new object());
 }
Exemple #47
0
 public void startRecv()
 {
     _listener = new UdpClient(Cmd.broadcast_port);
     _listener.BeginReceive(new AsyncCallback(recvMsg), null);
 }
Exemple #48
0
        //通讯连接
        public bool Init(string ip, int port, string localIp)
        {
            try
            {
                //ping PLC,看硬件是否能连上
                var ping = new Ping();
                var iep  = new IPEndPoint(IPAddress.Parse(ip), port);

                var pr = ping.Send(ip, 1000);
                if (pr.Status != IPStatus.Success)
                {
                    IsConnected = false;
                    return(false);
                }

                if (udpClient == null)
                {
                    udpClient = new UdpClient();
                    _struIP   = new StructIP();
                    dataSend  = new CmdData();
                }

                ipInfo          = new IPEndPoint(IPAddress.Parse(ip), port);
                _udpState       = new UdpState(udpClient, ipInfo);
                _struIP.ipPLC   = ip;
                _struIP.port    = port;
                _struIP.ipLocal = localIp;
                udpClient.Connect(ipInfo);
                var length = ip.Length;
                var index  = 0;
                for (var i = 0; i < length; i++)
                {
                    if ("." == ip.Substring(i, 1))
                    {
                        index++;
                        if (3 == index)
                        {
                            var ipLast = ip.Substring(i + 1, length - i - 1);
                            dataSend.DA1 = Convert.ToByte(ipLast);
                            break;
                        }
                    }
                }

                length = localIp.Length;
                index  = 0;
                for (var i = 0; i < length; i++)
                {
                    if ("." == localIp.Substring(i, 1))
                    {
                        index++;
                        if (3 == index)
                        {
                            var ipLast = localIp.Substring(i + 1, length - i - 1);
                            dataSend.SA1 = Convert.ToByte(ipLast);
                            break;
                        }
                    }
                }

                if (isInited == false)
                {
                    udpClient.BeginReceive(EndReceive, _udpState);
                    Thread.Sleep(500);
                    _boolTaskStart    = true;
                    _taskCheckConnect = new Task(CheckHeartThrob);
                    _taskCheckConnect.Start();
                }

                isInited = true;
                return(true);
            }
            catch
            {
                return(false);
            }
        }
 void Start()
 {
     X = new Queue<float> ();
     Y = new Queue<float> ();
     Z = new Queue<float> ();
     client = new UdpClient (port);
     ReceiveOperationInfo msgInfo = new ReceiveOperationInfo ();
     msgInfo.msgUDPClient = client;
     msgInfo.msgIPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),port);
     client.BeginReceive (new AsyncCallback (ReceiveDataAsync), msgInfo);
 }