Ejemplo n.º 1
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));
            }
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
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}");
            }
        }
Ejemplo n.º 4
0
        private void AsyncCallBackRecieve(IAsyncResult result)
        {
            byte[] received = _server.EndReceive(result, ref _address);

            _server.BeginReceive(new AsyncCallback(AsyncCallBackRecieve), null);
            string[] msg = Encoding.ASCII.GetString(received).Split('&');

            // reply port / hostname / message / [connection data | ( new_connection | disconnected) client_address

            if (msg.Length >= 4 && msg[3].Equals("new_connection"))
            {
                newClient = new Client()
                {
                    UserName      = msg[1],
                    ClientAddress = _address.Address,
                    ClientPort    = int.Parse(msg[0]),
                };
                UpdateConnectedClients(newClient);
            }
            if (msg.Length >= 4 && msg[3].Equals("disconnecting"))
            {
                var message = $"Client disconnected\n{msg[2]} disconnected";
                UpdateServerLog(message);
            }

            foreach (var client in listBoxConnectedClients.Items)
            {
                var refClient = client as Client;
                if (refClient != null && msg[0].Equals(refClient.ClientPort.ToString()))
                {
                    continue;
                }
                var message = $"[{msg[1]}] {msg[2]}";
                var buffer  = Encoding.ASCII.GetBytes(message);
                // should be sending to refClient.ClientAddress
                _server.Send(buffer, buffer.Length, new IPEndPoint(refClient.ClientAddress, refClient.ClientPort));
            }
            UpdateServerLog($"{msg[1]} : {msg[2]}");
        }
Ejemplo n.º 5
0
        private void Receive(IAsyncResult ar)
        {
            if (discoveryComplete) //Prevent ObjectDisposedException/NullReferenceException when the Close() function is called
            {
                return;
            }

            IPEndPoint ip = new IPEndPoint(IPAddress.Any, PORT_NUMBER);

            byte[] bytes    = udp.EndReceive(ar, ref ip);
            var    message  = Encoding.ASCII.GetString(Messaging.SmartHomeProtocolEncoder.Decrypt(bytes));
            var    sys_info = ((dynamic)JObject.Parse(message)).system.get_sysinfo;

            TPLinkSmartDevice device = null;
            string            model  = (string)sys_info.model;

            if (model.StartsWith("HS110"))
            {
                device = new TPLinkSmartMeterPlug(ip.Address.ToString());
            }
            else if (model.StartsWith("HS"))
            {
                device = new TPLinkSmartPlug(ip.Address.ToString());
            }
            else if (model.StartsWith("LB"))
            {
                device = new TPLinkSmartBulb(ip.Address.ToString());
            }

            if (device != null)
            {
                DiscoveredDevices.Add(device);
            }

            if (udp != null)
            {
                StartListening();
            }
        }
Ejemplo n.º 6
0
 private void RecvDataCallBack(IAsyncResult ar)
 {
     try
     {
         if (client != null)
         {
             RecvDatas.Add(client.EndReceive(ar, ref remoteEP));
         }
     }
     catch (Exception ex)
     {
         //异常处理
         Log.Error(ex, "RecvDataCallBack Error");
     }
     finally
     {
         if (client != null)
         {
             client.BeginReceive(RecvDataCallBack, null);
         }
     }
 }
Ejemplo n.º 7
0
        private void Receive(IAsyncResult res)
        {
            var groupEP = new IPEndPoint(IPAddress.Any, _port + 1);
            var data    = _udpClient.EndReceive(res, ref groupEP);

            var packet = ToClass <Packet>(data);

            if (_enabled)
            {
                switch (packet.PacketType)
                {
                case 0:
                    var telemetry = ToClass <sTelemetryData>(data);
                    if (Telemetry != null)
                    {
                        Telemetry(telemetry);
                    }
                    break;

                case 1:
                    var participantInfo = ToClass <sParticipantInfoStrings>(data);
                    if (ParticipantInfoStrings != null)
                    {
                        ParticipantInfoStrings(participantInfo);
                    }
                    break;

                case 2:
                    var additionalParticipantInfo = ToClass <sParticipantInfoStringsAdditional>(data);
                    if (ParticipantInfoStringsAdditional != null)
                    {
                        ParticipantInfoStringsAdditional(additionalParticipantInfo);
                    }
                    break;
                }

                _udpClient.BeginReceive(new AsyncCallback(Receive), null);
            }
        }
Ejemplo n.º 8
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))
                {
                    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);
                    }
                }
            }
        }
Ejemplo n.º 9
0
    /// <summary>
    /// This method continously listens for a reset command or a possible ipAddress to connect to
    /// </summary>
    /// <param name="result">The data that was recieved from the network</param>
    private void ReceiveData(IAsyncResult result)
    {
        IPEndPoint receiveIPGroup = new IPEndPoint(IPAddress.Any, NaviMobileManager.RemotePort);

        byte[] received;
        if (receiver != null)
        {
            received = receiver.EndReceive(result, ref receiveIPGroup);
        }
        else
        {
            return;
        }

        string message = Encoding.ASCII.GetString(received);

        if (message.Equals(RESET_STR))
        {
            if (TransformManagerInterface.Instance != null)
            {
                TransformManagerInterface.Instance.Reset();
            }
        }
        else
        {
            //assume that the message is an ipAddress
            byte error;
            if (naviConnectionID < 0)
            {
                if (!possibleConnections.Contains(message))
                {
                    possibleConnections.Add(message);                      //add ip to list
                }
            }
        }

        //start listening again
        receiver.BeginReceive(new AsyncCallback(ReceiveData), null);
    }
Ejemplo n.º 10
0
    private static void UDPReceiveCallback(IAsyncResult _result)
    {
        try
        {
            IPEndPoint _clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
            byte[]     _data           = udpListener.EndReceive(_result, ref _clientEndPoint);
            udpListener.BeginReceive(UDPReceiveCallback, null);

            Debug.Log("Pre lettura");
            if (_data.Length < 4)
            {
                return;
            }
            using (Packet _packet = new Packet(_data))
            {
                int _clientId = _packet.ReadInt();
                if (_clientId == 0)
                {
                    return;
                }
                if (clients[_clientId].udp.endPoint == null)
                {
                    // If this is a new connection
                    clients[_clientId].udp.Connect(_clientEndPoint);
                    return;
                }

                if (clients[_clientId].udp.endPoint.ToString() == _clientEndPoint.ToString())
                {
                    // Ensures that the client is not being impersonated by another by sending a false clientID
                    clients[_clientId].udp.HandleData(_packet);
                }
            }
        }
        catch (Exception _ex)
        {
            Debug.Log($"Error receiving UDP data: {_ex}");
        }
    }
Ejemplo n.º 11
0
        /// <summary>
        /// 当接收到回调
        /// </summary>
        /// <param name="result">结果</param>
        private void OnReceiveCallBack(IAsyncResult result)
        {
            try
            {
                var receiveBytes = (listenEndPoint == null) ?
                                   client.Receive(ref listenEndPoint) :
                                   client.EndReceive(result, ref listenEndPoint);

                if (receiveBytes == null || receiveBytes.Length <= 0)
                {
                    Dispose();
                    return;
                }

                receiveQueue.Push(receiveBytes);
                client.BeginReceive(OnReceiveCallBack, null);
            }
            catch (Exception)
            {
                Dispose();
            }
        }
Ejemplo n.º 12
0
    private static void UDPReceiveCallback(IAsyncResult ar)
    {
        try
        {
            IPEndPoint _clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
            byte[]     _data           = UdpListener.EndReceive(ar, ref _clientEndPoint);
            UdpListener.BeginReceive(UDPReceiveCallback, null);

            if (_data.Length < 4)
            {
                return;
            }

            using (Packet packet = new Packet(_data))
            {
                int _clientid = packet.ReadInt();

                if (_clientid == 0)
                {
                    return;
                }

                if (Clients[_clientid].udp.EndPoint == null)
                {
                    Clients[_clientid].udp.Connect(_clientEndPoint);
                    return;
                }

                if (Clients[_clientid].udp.EndPoint.ToString() == _clientEndPoint.ToString())
                {
                    Clients[_clientid].udp.HandleData(packet);
                }
            }
        }
        catch (Exception e)
        {
            Debug.Log($"Error receiving UDP data: {e}");
        }
    }
Ejemplo n.º 13
0
        private static void ReadCallbackUdp(IAsyncResult result)
        {
            if (_udpClientLisener != null)
            {
                try
                {
                    IPEndPoint ep           = (IPEndPoint)(result.AsyncState);
                    byte[]     receiveBytes = _udpClientLisener.EndReceive(result, ref ep);

                    ReceivedData(receiveBytes, comStatus.OK);
                    _udpClientLisener.BeginReceive(new AsyncCallback(ReadCallbackUdp), ep);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message);
                    Close();
                    ConnectUdp(_hostIP, _hostPort, _localPort, true);

                    //ReceivedData(new byte[0], comStatus.Close);
                }
            }
        }
Ejemplo n.º 14
0
        private void ProbeReceived(IAsyncResult ar)
        {
            var remote = new IPEndPoint(IPAddress.Any, 0);
            var bytes  = udp.EndReceive(ar, ref remote);

            // Compare beacon type to probe type
            var typeBytes = Encode(BeaconType);

            if (HasPrefix(bytes, typeBytes))
            {
                // If true, respond again with our type, port and payload
                var responseData = Encode(BeaconType)
                                   .Concat(BitConverter.GetBytes((ushort)IPAddress.HostToNetworkOrder((short)AdvertisedPort)))
                                   .Concat(Encode(BeaconData)).ToArray();
                udp.Send(responseData, responseData.Length, remote);
            }

            if (!Stopped)
            {
                udp.BeginReceive(ProbeReceived, null);
            }
        }
Ejemplo n.º 15
0
        private void Receive(IAsyncResult ar)
        {
            var ip = new IPEndPoint(IPAddress.Any, 32414);

            try
            {
                _udp.EndReceive(ar, ref ip);

                if (_listeners.Add(ip.Address.ToString()))
                {
                    StartListening();
                }
                else
                {
                    _listening = false;
                }
            }
            catch (Exception)
            {
                _listening = false;
            }
        }
Ejemplo n.º 16
0
        private void ReceiveCallback(IAsyncResult result)
        {
            try
            {
                byte[] data = socket.EndReceive(result, ref endPoint);

                socket.BeginReceive(ReceiveCallback, null);

                if (data.Length < 4)
                {
                    instance.Disconnect();
                    return;
                }

                HandleData(data);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"UDP receive failed: {ex}");
                Disconnect();
            }
        }
Ejemplo n.º 17
0
        private void RecvCallback(IAsyncResult ar)
        {
            recvState = null;
            UdpClient  udp      = (UdpClient)ar.AsyncState;
            IPEndPoint remoteEP = null;

            byte[] recvBytes = udp.EndReceive(ar, ref remoteEP);
            string recvText  = "";

            for (int i = 0; i < recvBytes.Length; i++)
            {
                recvText += recvBytes[i];
            }

            tbx_RecvData.BeginInvoke(new Action <string>(RecvTextShow), recvText);

            if (udpClientSend == null)
            {
                udpClientSend = new UdpClient();
            }
            udpClientSend.BeginSend(recvBytes, recvBytes.Length, remoteHost, remotePort, SendCallback, udpClientSend);
        }
Ejemplo n.º 18
0
 void HandleReceive(System.IAsyncResult ar)
 {
     try {
         if (_udp == null)
         {
             return;
         }
         var    clientEndpoint = new IPEndPoint(0, 0);
         byte[] receivedData   = _udp.EndReceive(ar, ref clientEndpoint);
         _oscParser.FeedData(receivedData, receivedData.Length);
         while (_oscParser.MessageCount > 0)
         {
             lock (_received) {
                 var msg = _oscParser.PopMessage();
                 Receive(new Capsule(msg, clientEndpoint));
             }
         }
     } catch (Exception e) {
         RaiseError(e);
     }
     _udp.BeginReceive(_callback, null);
 }
Ejemplo n.º 19
0
    private void ReceiveData(IAsyncResult result)
    {
        receiveIPGroup = new IPEndPoint(IPAddress.Any, remotePort);
        byte[] received;
        if (receiver != null)
        {
            received = receiver.EndReceive(result, ref receiveIPGroup);
        }
        else
        {
            return;
        }

        string receivedString = Encoding.ASCII.GetString(received);

        ipAddress          = receivedString;
        hasReceivedMessage = true;
        isReceiving        = false;
        receiver.Close();
        receiver = null;
        Debug.Log("Broadcast received! Stopped listening for broadcast");
    }
Ejemplo n.º 20
0
        private void OnConnection(IAsyncResult result)
        {
            try
            {
                byte[] data = udpClient.EndReceive(result, ref ipEndPoint);

                // Start listening for next connection again
                udpClient.BeginReceive(OnConnection, null);

                if (data.Length < sizeof(int))
                {
                    connectionToServer.Disconnect();
                    return;
                }

                HandlePacketData(data);
            }
            catch
            {
                connectionToServer.Disconnect();
            }
        }
Ejemplo n.º 21
0
        private void ReceiveCallback(IAsyncResult result)
        {
            try {
                byte[] data = Socket.EndReceive(result, ref EndPoint);
                Socket.BeginReceive(ReceiveCallback, null);

                if (data.Length < 4)
                {
                    Instance.Disconnect();
                    return;
                }

                HandleData(data);
            }
            catch (System.ObjectDisposedException) {
                Disconnect();
            }
            catch (Exception e) {
                Debug.Log($"Error receiving data via UDP: {e}");
                Disconnect();
            }
        }
    private static void UDPReceiveCallback(IAsyncResult _result)
    {
        try
        {
            IPEndPoint _clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
            byte[]     _data           = udpListener.EndReceive(_result, ref _clientEndPoint);
            udpListener.BeginReceive(UDPReceiveCallback, null);

            if (_data.Length < 4)
            {
                return;
            }

            using (Packet _packet = new Packet(_data))
            {
                int _clientId = _packet.ReadInt();

                if (_clientId == 0)
                {
                    return;
                }

                if (clients[_clientId].udp.endPoint == null)
                {
                    clients[_clientId].udp.Connect(_clientEndPoint);
                    return;
                }

                if (clients[_clientId].udp.endPoint.ToString() == _clientEndPoint.ToString())
                {
                    clients[_clientId].udp.HandleData(_packet);
                }
            }
        }
        catch (Exception _ex)
        {
            Console.WriteLine($"Error receiving UDP data: {_ex}");
        }
    }
Ejemplo n.º 23
0
        private void HandleClientPacketReceived(IAsyncResult result)
        {
            if (CommsCallback != null)
            {
                IPEndPoint endPoint  = new IPEndPoint(IPAddress.Any, 3007);
                byte[]     dataBytes = _client.EndReceive(result, ref endPoint);

                string data = Encoding.ASCII.GetString(dataBytes, 0, dataBytes.Length).Trim('\0');
                Android.Util.Log.Debug("Leda", "Received: " + data);

                if ((data.IndexOf(Game_Identifier) > -1) && (data.IndexOf(string.Concat("&id=", MyID)) < 0))
                {
                    Android.Util.Log.Debug("Leda", "Sent");
                    DecodeAndSendData(data);
                }
            }

            if (_clientOpen)
            {
                _client.BeginReceive(HandleClientPacketReceived, _client);
            }
        }
        private void ReceiveCallback(IAsyncResult AR)
        {
            try
            {
                byte[] data = socket.EndReceive(AR, ref endPoint);
                socket.BeginReceive(ReceiveCallback, null);

                if (data.Length < 4)
                {
                    Client client = GameObject.FindObjectOfType <Client>();
                    client.Disconnect();

                    return;
                }

                HandleData(data);
            }
            catch (Exception e)
            {
                Disconnect();
            }
        }
Ejemplo n.º 25
0
        public void Run()
        {
            stop = false;
            var ep = new IPEndPoint(IPAddress.Any, 0);

            Console.WriteLine("Listening on port " + port.ToString());

            while (!stop && udp.Client.IsBound)
            {
                var asyn = udp.BeginReceive((ar) => {
                    var data = udp.EndReceive(ar, ref ep);
                    ThreadPool.QueueUserWorkItem(clientThread, new Tuple <IPEndPoint, byte[]>(ep, data));
                }, null);

                if (!asyn.AsyncWaitHandle.WaitOne(waitTimeout))
                {
                    Console.WriteLine("Timeout - no package received during the last {0} seconds!\nShutting down!", waitTimeout / 1000);
                    Stop();
                    break;
                }
            }
        }
Ejemplo n.º 26
0
        private void Receive(IAsyncResult asyncResult)
        {
            try
            {
                var    remote = new IPEndPoint(IPAddress.Any, 0);
                byte[] buffer = _udp.EndReceive(asyncResult, ref remote);

                if (buffer != null && buffer.Length > 0 &&
                    Protocol.TryDecodeProbeMessage(buffer, out string remoteId) &&
                    Message.ServiceId.Equals(remoteId))
                {
                    byte[] response = Protocol.Encode(Message);
                    _udp.Send(response, response.Length, remote);
                }

                _udp.BeginReceive(Receive, null);
            }
            catch (ObjectDisposedException)
            {
                // Normal behavior of UdpClient/Socket to throw when closed.
            }
        }
    void OnReceive(IAsyncResult ar)
    {
        try
        {
            DataReceived dataReceived = new DataReceived();
            dataReceived.data = connection.EndReceive(ar, ref dataReceived.ipEndPoint);

            connection.BeginReceive(OnReceive, null);

            Debug.Log("OnReceive: " + dataReceived.data);

            lock (handler)
            {
                dataReceivedQueue.Enqueue(dataReceived);
            }
        }
        catch (SocketException e)
        {
            // This happens when a client disconnects, as we fail to send to that port.
            UnityEngine.Debug.LogError("[UdpConnection] " + e.Message);
        }
    }
Ejemplo n.º 28
0
        private static void UDPReceiveCallback(IAsyncResult result)
        {
            try
            {
                IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
                byte[]     data           = _udpListener.EndReceive(result, ref clientEndPoint);
                _udpListener.BeginReceive(UDPReceiveCallback, null);

                if (data.Length < 4)
                {
                    return;
                }

                using (Packet packet = new Packet(data))
                {
                    int clientId = packet.ReadInt();

                    if (clientId == 0)
                    {
                        return;
                    }

                    if (clients[clientId].udp.endPoint == null)
                    {
                        clients[clientId].udp.Connect(clientEndPoint);
                        return;
                    }

                    if (clients[clientId].udp.endPoint.ToString() == clientEndPoint.ToString())
                    {
                        clients[clientId].udp.HandleData(packet);
                    }
                }
            }
            catch (Exception e)
            {
                Log($"Error receiving UDP data: {e}");
            }
        }
Ejemplo n.º 29
0
    public void ReceiveCallback_LocalSurface(IAsyncResult ar)
    {
        Byte[] receiveBytes = _udpClient_LocalSurface.EndReceive(ar, ref _anyIP_LocalSurface);
        string result       = System.Text.Encoding.UTF8.GetString(receiveBytes);

        print("message received: " + result);

        if (SurfaceMessage.isMessage(result))
        {
            print("is surface");

            _surface = new SurfaceRectangle(result);

            Debug.Log("surface: " + _surface.ToString());

            _udpClient_LocalSurface.Close();
        }
        else
        {
            _udpClient_LocalSurface.BeginReceive(new AsyncCallback(this.ReceiveCallback_LocalSurface), null);
        }
    }
Ejemplo n.º 30
0
 void OnPingBack(IAsyncResult result)
 {
     try
     {
         IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
         ServerInfo si   = result.AsyncState as ServerInfo;
         UdpClient  c    = si.client;
         byte[]     data = c.EndReceive(result, ref RemoteIpEndPoint);
         if (data.Length == 3 && data[0] == 11 && data[2] == 1) // server info pkg and free slots
         {
             var time = DateTime.Now - si.pingSent;
             si.ping     = (int)time.TotalMilliseconds;
             si.gameMode = data[1];
             AppendToServerList(si);
         }
         c.Close();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
 }
Ejemplo n.º 31
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;
         }
     }
 }
Ejemplo n.º 32
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;
    }