private DpwsServiceDescriptions ProcessMatch(DpwsServiceDescription.ServiceDescriptionType type, WsMessage response, string messageID, IPEndPoint remoteEP, WsMessageCheck messageCheck)
        {
            Microsoft.SPOT.Debug.Assert(type == DpwsServiceDescription.ServiceDescriptionType.ProbeMatch ||
                                        type == DpwsServiceDescription.ServiceDescriptionType.ResolveMatch);

            // Parse and build header
            WsWsaHeader header = response.Header;
            XmlReader   reader = response.Reader;

            if (header == null || reader == null)
            {
                return(null);
            }

            try
            {
                // Make sure this is a probe matches response
                String headerAction = (type == DpwsServiceDescription.ServiceDescriptionType.ProbeMatch) ?
                                      m_version.DiscoveryNamespace + "/ProbeMatches" :
                                      m_version.DiscoveryNamespace + "/ResolveMatches";

                if (header.Action != headerAction)
                {
                    return(null);
                }

                // Make sure this is not a duplicate probe response
                if (messageCheck != null)
                {
                    if (messageCheck.IsDuplicate(header.MessageID, remoteEP.ToString()) == true)
                    {
                        System.Ext.Console.Write("ProbeMatches / ResolveMatches - Duplicate response - " + header.Action + " received");
                        return(null);
                    }
                }

                // Make sure the messageID matches the request ID
                if (header.RelatesTo != messageID)
                {
                    return(null);
                }

                // Process the probe matches
#if DEBUG
                int depth = reader.Depth;
#endif
                DpwsServiceDescriptions matches = new DpwsServiceDescriptions(reader, type, m_version, remoteEP);
#if DEBUG
                Microsoft.SPOT.Debug.Assert(XmlReaderHelper.HasReadCompleteNode(depth, reader));
#endif

                return(matches);
            }
            finally
            {
                reader.Close();
            }
        }
示例#2
0
        /// <summary>
        /// Sends a directed Probe request and parses ProbeMatches responses.
        /// </summary>
        /// <param name="endpointAddress">
        /// A string containing a Dpws devices transport endpoint address.
        /// For example: http://192.168.0.1:8084/3cb0d1ba-cc3a-46ce-b416-212ac2419b20
        /// </param>
        /// <param name="targetServiceAddress">
        /// A string containing the target service address to probe for.
        /// For example: urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b20
        /// </param>
        /// <param name="filters">
        /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match.
        /// Null = any type.
        /// </param>
        /// <remarks>
        /// A directed Probe is used to discover services on a network. The DirectedProbe method sends a
        /// HTTP request to the service specified endpointAddress parameter. A service at the endpoint that
        /// implements matching types specified in the filters parameter should respond with a ProbeMatches
        /// message. The ProbeMatches mesgage is returned as the response to the DirectedProbe request.
        /// If a null filter is supplied any Dpws complient service should reply with a ProbeMatches reponse.
        /// This method is used to directly ask for service endpoint information.
        /// </remarks>
        /// <returns>
        /// A collection of ProbeMatches objects.  A ProbeMatch object contains endpoint details used
        /// used to locate the actual service on a network and the types supported by the service.
        /// </returns>
        /// <exception cref="InvalidOperationException">If a fault response is received.</exception>
        public DpwsServiceDescriptions DirectedProbe(string endpointAddress, string targetServiceAddress, DpwsServiceTypes filters)
        {
            // Build the probe request message
            string messageID = null;

            byte[] probeRequest = BuildProbeRequest(targetServiceAddress, filters, out messageID);

            System.Ext.Console.Write("");
            System.Ext.Console.Write("Sending DirectedProbe:");
            System.Ext.Console.Write(new string(new UTF8Encoding().GetChars(probeRequest)));
            System.Ext.Console.Write("");

            // Create an http client and send the probe request. Use a WspHttpClient to get an array response.
            WsHttpClient httpClient = new WsHttpClient();

            byte[] probeResponse = httpClient.SendRequest(probeRequest, endpointAddress, false, false);

            // Build probe matches collection
            DpwsServiceDescriptions  probeMatches  = new DpwsServiceDescriptions();
            DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor();

            if (probeResponse != null)
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write("ProbeMatches Response From: " + endpointAddress);
                System.Ext.Console.Write(new String(System.Text.Encoding.UTF8.GetChars(probeResponse)));

                try
                {
                    DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(probeResponse, messageID, null, null);
                    if (tempMatches != null)
                    {
                        int count = tempMatches.Count;
                        for (int i = 0; i < count; i++)
                        {
                            probeMatches.Add(tempMatches[i]);
                        }
                    }
                }
                catch (Exception e)
                {
                    System.Ext.Console.Write("");
                    System.Ext.Console.Write(e.Message);
                    System.Ext.Console.Write("");
                }
            }

            if (probeMatches.Count == 0)
            {
                return(null);
            }
            else
            {
                return(probeMatches);
            }
        }
示例#3
0
        /// <summary>
        /// Sends a Probe request and parses ProbeMatches responses.
        /// </summary>
        /// <param name="filters">
        /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match.
        /// Null = any type.
        /// </param>
        /// <param name="maxProbeMatches">
        /// An integer representing the maximum number of matches to reveive within the timout period. Pass 0 to receive
        /// as many matches as possible before the timeout expires.
        /// </param>
        /// <param name="timeout">
        /// An integer specifying a request timeout in milliseconds. Pass -1 to wait ReceiveTimeout.
        /// </param>
        /// <remarks>
        /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the
        /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the
        /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast
        /// back to the that client that made the request. If a null filter is supplied any Dpws complient
        /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiceoveryCleint.ReceiveTimout
        /// for probe matches.
        /// </remarks>
        /// <returns>
        /// A collection of ProbeMatches objects.  A ProbeMatch object contains endpoint details used
        /// used to locate the actual service on a network and the types supported by the service.
        /// </returns>
        public DpwsServiceDescriptions Probe(DpwsServiceTypes filters, int maxProbeMatches, int timeout)
        {
            // Build the probe request message
            WsMessageCheck          messageCheck = new WsMessageCheck();
            string                  messageID    = null;
            WsMessage               probeRequest = BuildProbeRequest(DiscoVersion.DiscoveryWellKnownAddress, filters, out messageID);
            DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions();

            System.Ext.Console.Write("");
            System.Ext.Console.Write("Sending Probe:");
            System.Ext.Console.Write(probeRequest.Body as byte[]);
            System.Ext.Console.Write("");

            // Create a new UdpClient
            using (Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                // Very important - Set default multicast interface for the underlying socket

                uint       ipLocal = WsNetworkServices.GetLocalIPV4AddressValue();
                IPAddress  localIP = IPAddress.Parse(WsNetworkServices.GetLocalIPV4Address());
                IPEndPoint localEP = new IPEndPoint(localIP, 0);

                udpClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)ipLocal);
                udpClient.ReceiveTimeout = timeout;

                udpClient.Bind(localEP);

                // Random back off implemented as per soap over udp specification
                // for unreliable multicast message exchange
                Thread th = SendWithBackoff((byte[])probeRequest.Body, udpClient);

                // Create probe matches collection and set expiration loop timer
                byte[]   probeResponse = new byte[c_MaxUdpPacketSize];
                EndPoint remoteEP      = new IPEndPoint(IPAddress.Any, 0);
                int      responseLength;

                DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor(m_version);

                while (true)
                {
                    // Since MF sockets does not have an IOControl method catch 10054 to get around the problem
                    // with Upd and ICMP.
                    try
                    {
                        // Wait for response
                        responseLength = udpClient.ReceiveFrom(probeResponse, c_MaxUdpPacketSize, SocketFlags.None, ref remoteEP);
                    }
                    catch (SocketException se)
                    {
                        if ((SocketError)se.ErrorCode == SocketError.ConnectionReset)
                        {
                            Thread.Sleep(100);
                            continue;
                        }

                        // Timeout
                        if ((SocketError)se.ErrorCode == SocketError.TimedOut)
                        {
                            break;
                        }

                        throw se;
                    }

                    // If we received process probe match
                    if (responseLength > 0)
                    {
                        System.Ext.Console.Write("");
                        System.Ext.Console.Write("ProbeMatches Response From: " + ((IPEndPoint)remoteEP).Address.ToString());
                        System.Ext.Console.Write(probeResponse);

                        // Process the response
                        try
                        {
                            WsWsaHeader header = new WsWsaHeader();

                            XmlReader reader = WsSoapMessageParser.ParseSoapMessage(probeResponse, ref header, m_version);

                            WsMessage msg = new WsMessage(header, null, WsPrefix.Wsdp);

                            msg.Reader = reader;

                            DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(msg, messageID, (IPEndPoint)remoteEP, messageCheck);
                            if (tempMatches != null)
                            {
                                int count = maxProbeMatches < tempMatches.Count ? maxProbeMatches : tempMatches.Count;

                                for (int i = 0; i < count; i++)
                                {
                                    probeMatches.Add(tempMatches[i]);
                                }
                                maxProbeMatches -= count;
                            }
                        }
                        catch (Exception e)
                        {
                            System.Ext.Console.Write("");
                            System.Ext.Console.Write(e.Message);
                            System.Ext.Console.Write("");
                        }

                        // If maxProbeRequest is set check count
                        if (maxProbeMatches <= 0)
                        {
                            break;
                        }
                    }
                }

                th.Join();
            }

            // Display results
            if (probeMatches.Count == 0)
            {
                System.Ext.Console.Write("Probe timed out.");
            }
            else
            {
                System.Ext.Console.Write("Received " + probeMatches.Count + " probeMatches matches.");
            }

            return(probeMatches);
        }
        private DpwsServiceDescriptions ProcessMatch(DpwsServiceDescription.ServiceDescriptionType type, WsMessage response, string messageID, IPEndPoint remoteEP, WsMessageCheck messageCheck)
        {
            Microsoft.SPOT.Debug.Assert(type == DpwsServiceDescription.ServiceDescriptionType.ProbeMatch
                || type == DpwsServiceDescription.ServiceDescriptionType.ResolveMatch);

            // Parse and build header
            WsWsaHeader header = response.Header;
            XmlReader   reader = response.Reader;

            if(header == null || reader == null)
            {
                return null;
            }

            try
            {
                // Make sure this is a probe matches response
                String headerAction = (type == DpwsServiceDescription.ServiceDescriptionType.ProbeMatch) ?
                    m_version.DiscoveryNamespace + "/ProbeMatches" :
                    m_version.DiscoveryNamespace + "/ResolveMatches";

                if (header.Action != headerAction)
                    return null;

                // Make sure this is not a duplicate probe response
                if (messageCheck != null)
                {
                    if (messageCheck.IsDuplicate(header.MessageID, remoteEP.ToString()) == true)
                    {
                        System.Ext.Console.Write("ProbeMatches / ResolveMatches - Duplicate response - " + header.Action + " received");
                        return null;
                    }
                }

                // Make sure the messageID matches the request ID
                if (header.RelatesTo != messageID)
                    return null;

                // Process the probe matches
#if DEBUG
                int depth = reader.Depth;
#endif
                DpwsServiceDescriptions matches = new DpwsServiceDescriptions(reader, type, m_version, remoteEP);
#if DEBUG
                Microsoft.SPOT.Debug.Assert(XmlReaderHelper.HasReadCompleteNode(depth, reader));
#endif

                return matches;
            }
            finally
            {
                reader.Close();
            }
        }
        /// <summary>
        /// Sends a Probe request and parses ProbeMatches responses.
        /// </summary>
        /// <param name="filters">
        /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match.
        /// Null = any type.
        /// </param>
        /// <param name="maxProbeMatches">
        /// An integer representing the maximum number of matches to reveive within the timout period. Pass 0 to receive
        /// as many matches as possible before the timeout expires.
        /// </param>
        /// <param name="timeout">
        /// An integer specifying a request timeout in milliseconds. Pass -1 to wait ReceiveTimeout.
        /// </param>
        /// <remarks>
        /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the
        /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the
        /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast
        /// back to the that client that made the request. If a null filter is supplied any Dpws complient
        /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiceoveryCleint.ReceiveTimout
        /// for probe matches.
        /// </remarks>
        /// <returns>
        /// A collection of ProbeMatches objects.  A ProbeMatch object contains endpoint details used
        /// used to locate the actual service on a network and the types supported by the service.
        /// </returns>
        public DpwsServiceDescriptions Probe(DpwsServiceTypes filters, int maxProbeMatches, int timeout)
        {
            // Build the probe request message
            WsMessageCheck messageCheck = new WsMessageCheck();
            string messageID = null;
            WsMessage probeRequest = BuildProbeRequest(DiscoVersion.DiscoveryWellKnownAddress, filters, out messageID);
            DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions();

            System.Ext.Console.Write("");
            System.Ext.Console.Write("Sending Probe:");
            System.Ext.Console.Write(probeRequest.Body as byte[]);
            System.Ext.Console.Write("");

            // Create a new UdpClient
            using(Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(WsNetworkServices.GetLocalIPV4Address()), m_discoResponsePort);
                udpClient.Bind(localEP);

                // Very important - Set default multicast interface for the underlying socket
                udpClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)WsNetworkServices.GetLocalIPV4AddressValue());
                udpClient.ReceiveTimeout = timeout;

                // Random back off implemented as per soap over udp specification
                // for unreliable multicast message exchange
                Thread th = SendWithBackoff((byte[])probeRequest.Body, udpClient);

                // Create probe matches collection and set expiration loop timer
                byte[] probeResponse = new byte[c_MaxUdpPacketSize];
                EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                int responseLength;

                DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor(m_version);

                while (true)
                {
                    // Since MF sockets does not have an IOControl method catch 10054 to get around the problem
                    // with Upd and ICMP.
                    try
                    {
                        // Wait for response
                        responseLength = udpClient.ReceiveFrom(probeResponse, c_MaxUdpPacketSize, SocketFlags.None, ref remoteEP);
                    }
                    catch (SocketException se)
                    {
                        if ((SocketError)se.ErrorCode == SocketError.ConnectionReset)
                        {
                            Thread.Sleep(100);
                            continue;
                        }

                        // Timeout
                        if ((SocketError)se.ErrorCode == SocketError.TimedOut)
                            break;

                        throw se;
                    }

                    // If we received process probe match
                    if (responseLength > 0)
                    {
                        System.Ext.Console.Write("");
                        System.Ext.Console.Write("ProbeMatches Response From: " + ((IPEndPoint)remoteEP).Address.ToString());
                        System.Ext.Console.Write(probeResponse);

                        // Process the response
                        try
                        {
                            WsWsaHeader header = new WsWsaHeader();
                            
                            XmlReader reader = WsSoapMessageParser.ParseSoapMessage(probeResponse, ref header, m_version);
                            
                            WsMessage msg = new WsMessage(header, null, WsPrefix.Wsdp);

                            msg.Reader = reader;

                            DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(msg, messageID, (IPEndPoint)remoteEP, messageCheck);
                            if (tempMatches != null)
                            {
                                int count = maxProbeMatches < tempMatches.Count ? maxProbeMatches : tempMatches.Count;

                                for (int i = 0; i < count; i++)
                                {
                                    probeMatches.Add(tempMatches[i]);
                                }
                                maxProbeMatches -= count;
                            }
                        }
                        catch (Exception e)
                        {
                            System.Ext.Console.Write("");
                            System.Ext.Console.Write(e.Message);
                            System.Ext.Console.Write("");
                        }

                        // If maxProbeRequest is set check count
                        if (maxProbeMatches <= 0)
                        {
                            break;
                        }
                        
                    }
                }

                th.Join();
            }

            // Display results
            if (probeMatches.Count == 0)
                System.Ext.Console.Write("Probe timed out.");
            else
                System.Ext.Console.Write("Received " + probeMatches.Count + " probeMatches matches.");

            return probeMatches;
        }
        /// <summary>
        /// Sends a directed Probe request and parses ProbeMatches responses.
        /// </summary>
        /// <param name="endpointAddress">
        /// A string containing a Dpws devices transport endpoint address.
        /// For example: http://192.168.0.1:8084/3cb0d1ba-cc3a-46ce-b416-212ac2419b20
        /// </param>
        /// <param name="targetServiceAddress">
        /// A string containing the target service address to probe for.
        /// For example: urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b20
        /// </param>
        /// <param name="filters">
        /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match.
        /// Null = any type.
        /// </param>
        /// <remarks>
        /// A directed Probe is used to discover services on a network. The DirectedProbe method sends a
        /// HTTP request to the service specified endpointAddress parameter. A service at the endpoint that
        /// implements matching types specified in the filters parameter should respond with a ProbeMatches
        /// message. The ProbeMatches mesgage is returned as the response to the DirectedProbe request.
        /// If a null filter is supplied any Dpws complient service should reply with a ProbeMatches reponse.
        /// This method is used to directly ask for service endpoint information.
        /// </remarks>
        /// <returns>
        /// A collection of ProbeMatches objects.  A ProbeMatch object contains endpoint details used
        /// used to locate the actual service on a network and the types supported by the service.
        /// </returns>
        /// <exception cref="InvalidOperationException">If a fault response is received.</exception>
        public DpwsServiceDescriptions DirectedProbe(string endpointAddress, string targetServiceAddress, DpwsServiceTypes filters)
        {
            // Build the probe request message
            string messageID = null;
            WsMessage probeRequest = BuildProbeRequest(targetServiceAddress, filters, out messageID);

            System.Ext.Console.Write("");
            System.Ext.Console.Write("Sending DirectedProbe:");
            System.Ext.Console.Write(probeRequest.Body as byte[]);
            System.Ext.Console.Write("");

            // Create an http client and send the probe request. Use a WspHttpClient to get an array response.
            WsHttpClient httpClient = new WsHttpClient(m_version);

            WsMessage probeResponse = httpClient.SendRequest(probeRequest, new Uri(endpointAddress));

            // Build probe matches collection
            DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions();
            DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor(m_version);
            if (probeResponse != null)
            {
                System.Ext.Console.Write("");
                System.Ext.Console.Write("ProbeMatches Response From: " + endpointAddress);
                System.Ext.Console.Write(probeResponse.Body as byte[]);

                try
                {
                    DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(probeResponse, messageID, null, null);
                    if (tempMatches != null)
                    {
                        int count = tempMatches.Count;
                        for (int i = 0; i < count; i++)
                        {
                            probeMatches.Add(tempMatches[i]);
                        }
                    }
                }
                catch (Exception e)
                {
                    System.Ext.Console.Write("");
                    System.Ext.Console.Write(e.Message);
                    System.Ext.Console.Write("");
                }
            }

            if (probeMatches.Count == 0)
                return null;
            else
                return probeMatches;
        }
        /// <summary>
        /// Parses a ResolveMatches message.
        /// </summary>
        /// <param name="resolveResponse">A byte array containing a resolve response soap message.</param>
        /// <param name="messageID">
        /// A string containing the message ID of the original request. This is used to make insure this is
        /// a response to the original request.
        /// </param>
        /// <param name="remoteEP">
        /// A IPEndPoint containing the remote address of the service that sent this response.
        /// </param>
        /// <param name="messageCheck">
        /// A WsdMessageCheck object ued to test for a duplicate request message.
        /// If null no check is performed as would be the case for a directed probe response.
        /// </param>
        /// <returns>
        /// A DpwsResolveMatch object containing a service endpoint description returned by a service.
        /// </returns>
        /// <exception cref="XmlException">If required tags are missing or invalid namespaces are detected.</exception>
        public DpwsServiceDescription ProcessResolveMatch(WsMessage resolveResponse, string messageID, IPEndPoint remoteEP, WsMessageCheck messageCheck)
        {
            DpwsServiceDescriptions resolveMatches = ProcessMatch(DpwsServiceDescription.ServiceDescriptionType.ResolveMatch, resolveResponse, messageID, remoteEP, messageCheck);

            return(resolveMatches == null ? null : resolveMatches[0]);
        }
示例#8
0
        /// <summary>
        /// Sends a Probe request and parses ProbeMatches responses.
        /// </summary>
        /// <param name="filters">
        /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match.
        /// Null = any type.
        /// </param>
        /// <param name="maxProbeMatches">
        /// An integer representing the maximum number of matches to reveive within the timout period. Pass 0 to receive
        /// as many matches as possible before the timeout expires.
        /// </param>
        /// <param name="timeout">
        /// An integer specifying a request timeout in milliseconds. Pass -1 to wait ReceiveTimeout.
        /// </param>
        /// <remarks>
        /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the
        /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the
        /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast
        /// back to the that client that made the request. If a null filter is supplied any Dpws complient
        /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiceoveryCleint.ReceiveTimout
        /// for probe matches.
        /// </remarks>
        /// <returns>
        /// A collection of ProbeMatches objects.  A ProbeMatch object contains endpoint details used
        /// used to locate the actual service on a network and the types supported by the service.
        /// </returns>
        public DpwsServiceDescriptions Probe(DpwsServiceTypes filters, int maxProbeMatches, int timeout)
        {
            // Build the probe request message
            WsMessageCheck messageCheck = new WsMessageCheck();
            string messageID = null;
            byte[] probeRequest = BuildProbeRequest(DiscoVersion.WellKnownAddress, filters, out messageID);

            System.Ext.Console.Write("");
            System.Ext.Console.Write("Sending Probe:");
            System.Ext.Console.Write(new string(new UTF8Encoding().GetChars(probeRequest)));
            System.Ext.Console.Write("");

            // Create a new UdpClient
            Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, m_discoResponsePort);
            udpClient.Bind(localEP);

            // Very important - Set default multicast interface for the underlying socket
            byte[] ipBytes = IPAddress.Parse(WsNetworkServices.GetLocalIPV4Address()).GetAddressBytes();
            long longIP = (long)((ipBytes[0] + (ipBytes[1] << 0x08) + (ipBytes[2] << 0x10) + (ipBytes[3] << 0x18)) & 0xFFFFFFFF);
            udpClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)longIP);

            // Random back off implemented as per soap over udp specification
            // for unreliable multicast message exchange
            SendWithBackoff(probeRequest, udpClient);

            // Create probe matches collection and set expiration loop timer
            DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions();
            byte[] probeResponse = new byte[c_MaxUdpPacketSize];
            EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
            int responseLength;

            // Multiply receive time by 10000 to convert milliseconds to 100 nano ticks
            long endTime = (long)(DateTime.Now.Ticks + (timeout < 0 ? m_receiveTimeout * 10000 : timeout * 10000));
            DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor();

            // Build probe matches collection as long as timeout has not expired
            int noReceived = 0;

            while (DateTime.Now.Ticks < endTime)
            {
                if (udpClient.Available > 0)
                {
                    // If maxProbeRequest is set check count
                    if (maxProbeMatches > 0)
                    {
                        if (noReceived > maxProbeMatches)
                            break;
                    }

                    // Since MF sockets does not have an IOControl method catch 10054 to get around the problem
                    // with Upd and ICMP.
                    try
                    {
                        // Wait for response
                        responseLength = udpClient.ReceiveFrom(probeResponse, c_MaxUdpPacketSize, SocketFlags.None, ref remoteEP);
                    }
                    catch (SocketException se)
                    {
                        if (se.ErrorCode == 10054)
                            continue;
                        throw se;
                    }

                    // If we received process probe match
                    if (responseLength > 0)
                    {
                        System.Ext.Console.Write("");
                        System.Ext.Console.Write("ProbeMatches Response From: " + ((IPEndPoint)remoteEP).Address.ToString());
                        System.Ext.Console.Write(new String(System.Text.Encoding.UTF8.GetChars(probeResponse)));

                        // Process the response
                        try
                        {
                            DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(probeResponse, messageID, (IPEndPoint)remoteEP, messageCheck);
                            if (tempMatches != null)
                            {
                                int count = tempMatches.Count;
                                for (int i = 0; i < count; i++)
                                {
                                    probeMatches.Add(tempMatches[i]);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            System.Ext.Console.Write("");
                            System.Ext.Console.Write(e.Message);
                            System.Ext.Console.Write("");
                        }

                        // Increment the number received counter
                        ++noReceived;
                    }
                }
                else
                {
                    Thread.Sleep(1);
                }
            }

            udpClient.Close();
            udpClient = null;

            // Display results
            if (probeMatches == null)
                System.Ext.Console.Write("Probe timed out.");
            else
                System.Ext.Console.Write("Received " + probeMatches.Count + " probeMatches matches.");

            return probeMatches;
        }
示例#9
0
        /// <summary>
        /// Sends a Probe request and parses ProbeMatches responses.
        /// </summary>
        /// <param name="filters">
        /// A DpwsServiceTypes object containing a collection of types a service must support to signal a match.
        /// Null = any type.
        /// </param>
        /// <param name="maxProbeMatches">
        /// An integer representing the maximum number of matches to reveive within the timout period. Pass 0 to receive
        /// as many matches as possible before the timeout expires.
        /// </param>
        /// <param name="timeout">
        /// An integer specifying a request timeout in milliseconds. Pass -1 to wait ReceiveTimeout.
        /// </param>
        /// <remarks>
        /// A Probe is used to discover services on a network. The Probe method sends a UDP request to the
        /// Dpws multicast address, 239.255.255.250:3702. Any service that implements types specified in the
        /// filters parameter should respond with a ProbeMatches message. The ProbeMatches mesgage is unicast
        /// back to the that client that made the request. If a null filter is supplied any Dpws complient
        /// service should reply with a ProbeMatches reponse. Probe waits DpwsDiceoveryCleint.ReceiveTimout
        /// for probe matches.
        /// </remarks>
        /// <returns>
        /// A collection of ProbeMatches objects.  A ProbeMatch object contains endpoint details used
        /// used to locate the actual service on a network and the types supported by the service.
        /// </returns>
        public DpwsServiceDescriptions Probe(DpwsServiceTypes filters, int maxProbeMatches, int timeout)
        {
            // Build the probe request message
            WsMessageCheck messageCheck = new WsMessageCheck();
            string         messageID    = null;

            byte[] probeRequest = BuildProbeRequest(DiscoVersion.WellKnownAddress, filters, out messageID);

            System.Ext.Console.Write("");
            System.Ext.Console.Write("Sending Probe:");
            System.Ext.Console.Write(new string(new UTF8Encoding().GetChars(probeRequest)));
            System.Ext.Console.Write("");

            // Create a new UdpClient
            Socket     udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint localEP   = new IPEndPoint(IPAddress.Any, m_discoResponsePort);

            udpClient.Bind(localEP);

            // Very important - Set default multicast interface for the underlying socket
            byte[] ipBytes = IPAddress.Parse(WsNetworkServices.GetLocalIPV4Address()).GetAddressBytes();
            long   longIP  = (long)((ipBytes[0] + (ipBytes[1] << 0x08) + (ipBytes[2] << 0x10) + (ipBytes[3] << 0x18)) & 0xFFFFFFFF);

            udpClient.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)longIP);

            // Random back off implemented as per soap over udp specification
            // for unreliable multicast message exchange
            SendWithBackoff(probeRequest, udpClient);

            // Create probe matches collection and set expiration loop timer
            DpwsServiceDescriptions probeMatches = new DpwsServiceDescriptions();

            byte[]   probeResponse = new byte[c_MaxUdpPacketSize];
            EndPoint remoteEP      = new IPEndPoint(IPAddress.Any, 0);
            int      responseLength;

            // Multiply receive time by 10000 to convert milliseconds to 100 nano ticks
            long endTime = (long)(DateTime.Now.Ticks + (timeout < 0 ? m_receiveTimeout * 10000 : timeout * 10000));
            DpwsDiscoClientProcessor soapProcessor = new DpwsDiscoClientProcessor();

            // Build probe matches collection as long as timeout has not expired
            int noReceived = 0;

            while (DateTime.Now.Ticks < endTime)
            {
                if (udpClient.Available > 0)
                {
                    // If maxProbeRequest is set check count
                    if (maxProbeMatches > 0)
                    {
                        if (noReceived > maxProbeMatches)
                        {
                            break;
                        }
                    }

                    // Since MF sockets does not have an IOControl method catch 10054 to get around the problem
                    // with Upd and ICMP.
                    try
                    {
                        // Wait for response
                        responseLength = udpClient.ReceiveFrom(probeResponse, c_MaxUdpPacketSize, SocketFlags.None, ref remoteEP);
                    }
                    catch (SocketException se)
                    {
                        if (se.ErrorCode == 10054)
                        {
                            continue;
                        }
                        throw se;
                    }

                    // If we received process probe match
                    if (responseLength > 0)
                    {
                        System.Ext.Console.Write("");
                        System.Ext.Console.Write("ProbeMatches Response From: " + ((IPEndPoint)remoteEP).Address.ToString());
                        System.Ext.Console.Write(new String(System.Text.Encoding.UTF8.GetChars(probeResponse)));

                        // Process the response
                        try
                        {
                            DpwsServiceDescriptions tempMatches = soapProcessor.ProcessProbeMatch(probeResponse, messageID, (IPEndPoint)remoteEP, messageCheck);
                            if (tempMatches != null)
                            {
                                int count = tempMatches.Count;
                                for (int i = 0; i < count; i++)
                                {
                                    probeMatches.Add(tempMatches[i]);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            System.Ext.Console.Write("");
                            System.Ext.Console.Write(e.Message);
                            System.Ext.Console.Write("");
                        }

                        // Increment the number received counter
                        ++noReceived;
                    }
                }
                else
                {
                    Thread.Sleep(1);
                }
            }

            udpClient.Close();
            udpClient = null;

            // Display results
            if (probeMatches == null)
            {
                System.Ext.Console.Write("Probe timed out.");
            }
            else
            {
                System.Ext.Console.Write("Received " + probeMatches.Count + " probeMatches matches.");
            }

            return(probeMatches);
        }