예제 #1
0
        /// <summary>
        /// Creates a multicast listener on the specified multicast port,
        /// bound to the specified multicast group.  Whenever the byte[]
        /// pattern specified by "expectedMessage" is received, the byte[]
        /// pattern specifed by "returnMessage" is sent to the sender of
        /// the "expected message".
        /// </summary>
        /// <param name="multicastPort"> Port to bind this listener to. </param>
        /// <param name="multicastGroup"> Group to bind this listener to. </param>
        /// <param name="expectedMessage"> the message to look for </param>
        /// <param name="returnMessage"> the message to reply with </param>
        public MulticastListener(int multicastPort, string multicastGroup, byte[] expectedMessage, byte[] returnMessage)
        {
            this.expectedMessage = expectedMessage;
            this.returnMessage   = returnMessage;

            OneWireEventSource.Log.Debug("DEBUG: Creating Multicast Listener");
            OneWireEventSource.Log.Debug("DEBUG:    Multicast port: " + multicastPort);
            OneWireEventSource.Log.Debug("DEBUG:    Multicast group: " + multicastGroup);

            // create multicast socket
            socket = new DatagramSocket(); // MulticastSocket(multicastPort);
            socket.MessageReceived      += Multicast_MessageReceived;
            socket.Control.MulticastOnly = true;
            handlingPacket = false;

            var t = Task.Run(async() =>
            {
                // specify IP address of adapter...
                await socket.BindEndpointAsync(new HostName("localhost"), Convert.ToString(multicastPort));
            });

            t.Wait();

            //join the multicast group
            socket.JoinMulticastGroup(new HostName(multicastGroup));

            OneWireEventSource.Log.Debug("DEBUG: waiting for multicast packet");
        }
예제 #2
0
 public async Task <bool> InitializeRecv()
 {
     recvInitialized = false;
     try
     {
         if (msocketRecv != null)
         {
             msocketRecv.MessageReceived -= UDPMulticastMessageReceived;
             msocketRecv.Dispose();
             msocketRecv = null;
         }
         msocketRecv = new DatagramSocket();
         msocketRecv.MessageReceived += UDPMulticastMessageReceived;
         NetworkAdapter adapter = GetDefaultNetworkAdapter();
         if (adapter != null)
         {
             await msocketRecv.BindServiceNameAsync(mPort);
         }
         //              await msocketRecv.BindServiceNameAsync(mPort, adapter);
         else
         {
             await msocketRecv.BindServiceNameAsync(mPort);
         }
         HostName mcast = new HostName(mAddress);
         msocketRecv.JoinMulticastGroup(mcast);
         mLastIDReceived = 0;
         recvInitialized = true;
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine("Exception while listening: " + e.Message);
         recvInitialized = false;
     }
     return(recvInitialized);
 }
예제 #3
0
        public IAsyncAction Start()
        {
            return(Task.Run(async() =>
            {
                if (isStarted)
                {
                    return;
                }

                multicastSsdpSocket = new DatagramSocket();
                multicastSsdpSocket.MessageReceived += MulticastSsdpSocket_MessageReceived;
                multicastSsdpSocket.Control.MulticastOnly = true;
                await multicastSsdpSocket.BindServiceNameAsync(Constants.SSDP_PORT);
                multicastSsdpSocket.JoinMulticastGroup(Constants.SSDP_HOST);

                unicastLocalSocket = new DatagramSocket();
                unicastLocalSocket.MessageReceived += UnicastLocalSocket_MessageReceived;
                await unicastLocalSocket.BindServiceNameAsync("");
                logger.WriteLine($"ControlPoint: Bind to port :{unicastLocalSocket.Information.LocalPort} for UNICAST search responses.");

                NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;

                networks = GetNetworks();

                isStarted = true;

                logger.WriteLine("ControlPoint started.");
            }).AsAsyncAction());
        }
예제 #4
0
 async Task <bool> InitializeMulticastRecv()
 {
     try
     {
         if (msocketRecv != null)
         {
             msocketRecv.MessageReceived -= UDPMulticastMessageReceived;
             msocketRecv.Dispose();
             msocketRecv = null;
         }
         msocketRecv = new DatagramSocket();
         msocketRecv.Control.MulticastOnly = true;
         msocketRecv.MessageReceived      += UDPMulticastMessageReceived;
         NetworkAdapter adapter = GetDefaultNetworkAdapter(SendInterfaceAddress);
         if (adapter != null)
         {
             await msocketRecv.BindServiceNameAsync(MulticastUDPPort.ToString(), adapter);
         }
         else
         {
             await msocketRecv.BindServiceNameAsync(MulticastUDPPort.ToString());
         }
         HostName mcast = new HostName(MulticastIPAddress);
         msocketRecv.JoinMulticastGroup(mcast);
         return(true);
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine("Exception while listening: " + e.Message);
     }
     return(false);
 }
예제 #5
0
        public static async void init(TiSettings settings)
        {
            if (!settings.ContainsKey("logToken") || settings["logToken"].Length == 0)
            {
                return;
            }

            logToken = settings["logToken"];

            multicastSocket = new DatagramSocket();
            multicastSocket.MessageReceived += multicastSocket_MessageReceived;

            HostName hostname = new HostName("239.6.6.6");

            try {
                await multicastSocket.BindServiceNameAsync("8666");

                multicastSocket.JoinMulticastGroup(hostname);

                IOutputStream stream = await multicastSocket.GetOutputStreamAsync(hostname, "8666");

                DataWriter writer = new DataWriter(stream);
                writer.WriteString("TI_WP8_LOGGER");
                await writer.StoreAsync();

                writer.DetachStream();
                stream.Dispose();
            } catch (Exception ex) {
                if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }
                Debug.WriteLine(ex.ToString());
            }
        }
예제 #6
0
        private async void NetworkInformation_NetworkStatusChanged(object sender)
        {
            logger.WriteLine("Network status changed");
            var newNetworks = GetNetworks();

            var goneNetworkIds = networks
                                 .Select(n => n.NetworkAdapter.NetworkAdapterId)
                                 .Where(id => !newNetworks.Any(n => n.NetworkAdapter.NetworkAdapterId == id)).ToList();

            foreach (var networkId in goneNetworkIds)
            {
                if (NetworkGone != null)
                {
                    await dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                              new DispatchedHandler(() =>
                    {
                        NetworkGone?.Invoke(this, networkId);
                    }));
                }
            }

            networks = newNetworks;
            multicastSsdpSocket.JoinMulticastGroup(Constants.SSDP_HOST);
            await SearchDevices();
        }
예제 #7
0
 public override void StartClient(string address, int port)
 {
     socket_  = new DatagramSocket();
     sendHost = new HostName(address);
     sendPort = port.ToString();
     socket_.JoinMulticastGroup(sendHost);//この辺でjoinする
 }
예제 #8
0
        static async Task BindToSocketAndWriteQuery(DatagramSocket socket, byte[] bytes, CancellationToken cancellationToken)
        {
#if WINDOWS_UWP
            // Set control option for multicast. This enables re-use of the port, which is always in use under Windows 10 otherwise.
            socket.Control.MulticastOnly = true;
#endif
            await socket.BindServiceNameAsync("5353") // binds to the local IP addresses of all network interfaces on the local computer if no adapter is specified
            .AsTask(cancellationToken)
            .ConfigureAwait(false);

            socket.JoinMulticastGroup(new HostName("224.0.0.251"));
            var os = await socket.GetOutputStreamAsync(new HostName("224.0.0.251"), "5353")
                     .AsTask(cancellationToken)
                     .ConfigureAwait(false);

            using (var writer = new DataWriter(os))
            {
                writer.WriteBytes(bytes);
                await writer.StoreAsync()
                .AsTask(cancellationToken)
                .ConfigureAwait(false);

                Debug.WriteLine("Sent mDNS query");

                writer.DetachStream();
            }
        }
예제 #9
0
        private async void ListenSSDP_Click(object sender, RoutedEventArgs e)
        {
            socket = new DatagramSocket();
            socket.MessageReceived += (s, args) =>
            {
                var    reader  = args.GetDataReader();
                var    data    = reader.ReadString(reader.UnconsumedBufferLength);
                string address = $"{args.RemoteAddress.CanonicalName}:{args.RemotePort}";
                logger.WriteLine($"MULTICAST [{address}]\n{data}");
            };
            socket.Control.MulticastOnly = true;
            await socket.BindServiceNameAsync(Constants.SSDP_PORT);

            socket.JoinMulticastGroup(Constants.SSDP_HOST);
            NetworkInformation.NetworkStatusChanged += (s) => socket.JoinMulticastGroup(Constants.SSDP_HOST);
            logger.WriteLine($"Start listening multicast {Constants.SSDP_ADDRESS}");
        }
        private static async Task OpenSharedChannelAsync()
        {
            await _mutex.WaitAsync().ConfigureAwait(false);

            if (IsJoined || !_shouldJoinChannel)
            {
                return;
            }

            CloseSharedChannel();

            _log.Info("Opening shared MDNS channel...");

            while (!IsJoined && _shouldJoinChannel)
            {
                try
                {
                    // Create new socket
                    _udpSocket = new DatagramSocket();
                    _udpSocket.MessageReceived += UDPSocket_MessageReceived;

                    // Fixing an issue on Windows 8.1 by attaching the socket to the Internet connection profile's network adapter.
                    // Source: http://blogs.msdn.com/b/wsdevsol/archive/2013/12/19/datagramsocket-multicast-functionality-on-windows-8-1-throws-an-error-0x80072af9-wsahost-not-found.aspx
                    var networkAdapter = NetworkInformation.GetInternetConnectionProfile().NetworkAdapter;

                    // Bind the service name and join the multicast group
                    _log.Debug("Opening UDP socket...");
                    await _udpSocket.BindServiceNameAsync(BonjourUtility.MulticastDNSPort.ToString(), networkAdapter).AsTask().ConfigureAwait(false);

                    _log.Debug("Joining multicast group...");
                    _udpSocket.JoinMulticastGroup(_mdnsHostName);

                    // All done
                    IsJoined = true;
                }
                catch (Exception e)
                {
                    _log.Warning("Caught exception while opening UDP socket");
                    _log.Debug("Exception details: " + e.ToString());
                    CloseSharedChannel();
                }

                if (!IsJoined)
                {
                    await Task.Delay(1000).ConfigureAwait(false);
                }
                else
                {
                    _log.Info("Successfully opened shared MDNS channel.");
                }
            }


            _mutex.Release();
        }
        private async Task BindToLan(string port)
        {
        #if UNITY_EDITOR
            var p = int.Parse(port);
            using (var socket = new UdpClient(p)) {
                socket.JoinMulticastGroup(IPAddress.Parse(Multicast));
                Logs.Log($"UDP ready");
                while (true)
                {
                    var rec = await socket.ReceiveAsync();

                    var time = DateTime.Now;
                    Logs.Log($"Udp message received");
                    var str = Encoding.Default.GetString(rec.Buffer);
                    if (str != "IP?")
                    {
                        Logs.LogWarning($"Bad message");
                        continue;
                    }

                    var rep = Encoding.Default.GetBytes("IP!");
                    await socket.SendAsync(rep, rep.Length, rec.RemoteEndPoint);

                    Logs.Log($"Answer sent in {DateTime.Now - time}");
                }
            }
                                #elif UNITY_WSA
            using (var _socket = new DatagramSocket()) {
                await _socket.BindServiceNameAsync(port);

                _socket.JoinMulticastGroup(new HostName(Multicast));
                _socket.MessageReceived += async(sender, args) => {
                    Logs.Log($"Received message from {args.RemoteAddress}:{args.RemotePort}");
                    using (var output = new DataWriter(await sender.GetOutputStreamAsync(args.RemoteAddress, args.RemotePort))) {
                        string read;
                        using (var reader = args.GetDataReader()) { read = reader.ReadString(reader.UnconsumedBufferLength); }

                        if (read != "IP?")
                        {
                            return;
                        }
                        output.WriteString("IP!");
                        await output.StoreAsync();

                        await output.FlushAsync();
                    }
                };

                while (true)
                {
                    await Task.Delay(new TimeSpan(0, 0, 1));
                }
            }
        #endif
        }
예제 #12
0
        public async Task SsdpQueryAsync(string filter = "ssdp:all", int seconds = 5, int port = 1900)
        {
            _ssdpPort     = port;
            _foundDevices = new List <string>();
            var remoteIP  = new Windows.Networking.HostName(_ssdp_ip);
            var ssdpQuery = GetSSDPQuery(seconds, port, filter);
            var reqBuff   = Encoding.UTF8.GetBytes(ssdpQuery);

            try
            {
                if (_readerSocket != null)
                {
                    _readerSocket.Dispose();
                }
            }
            catch (Exception ex)
            {
                LogException("SSDPFinder.QueryAsync - Close Existing Socket", ex);
            }

            _readerSocket = new DatagramSocket();
            _readerSocket.MessageReceived += (sender, args) =>
            {
                Task.Run(async() =>
                {
                    var addr         = args.RemoteAddress.DisplayName;
                    var result       = args.GetDataStream();
                    var resultStream = result.AsStreamForRead(1024);

                    using (var reader = new StreamReader(resultStream))
                    {
                        var resultText = await reader.ReadToEndAsync();

                        if (resultText.StartsWith("HTTP/1.1 200 OK"))
                        {
                            HandleSSDPResponse(resultText);
                        }
                    };
                });
            };

            var ipAddress = PlatformSupport.Services.Network.GetIPV4Address();
            var hostName  = new Windows.Networking.HostName(ipAddress);
            await _readerSocket.BindEndpointAsync(hostName, "");

            Core.PlatformSupport.Services.Logger.AddCustomEvent(LogLevel.Message, "SSDPFinder.QueryAsync", _readerSocket.Information.LocalAddress + " " + _readerSocket.Information.LocalPort);

            _readerSocket.JoinMulticastGroup(remoteIP);

            using (var stream = await _readerSocket.GetOutputStreamAsync(remoteIP, _ssdpPort.ToString()))
            {
                await stream.WriteAsync(reqBuff.AsBuffer());
            }
        }
        public void addMembership(string mcastAddr, string ifaceAddr)
        {
            _socket.JoinMulticastGroup(new HostName(mcastAddr));

            if (ifaceAddr != string.Empty && ifaceAddr != null)
            {
                throw new NotImplementedException();
            }

            // TO DO ICommsInterface
        }
예제 #14
0
        /// <summary>
        /// initialize multicast
        /// </summary>
        private async void multi_cast()
        {
            listenerSocket = new DatagramSocket();              //datagram object
            listenerSocket.MessageReceived += MessageReceived;  //MessageReceived event
            //listenerSocket.MessageReceived += MessageReceived;
            listenerSocket.Control.MulticastOnly = true;

            await listenerSocket.BindServiceNameAsync("22113");

            listenerSocket.JoinMulticastGroup(new HostName("224.3.0.5"));
        }
예제 #15
0
        /// <summary>
        ///     Searches for an available devices of specified type.
        /// </summary>
        /// <param name="searchTarget">
        ///     The type of the devices to search for.
        /// </param>
        /// <param name="timeForResponse">
        ///     The time (in seconds) of a search.
        /// </param>
        /// <returns>
        ///     An observable collection which contains search results.
        /// </returns>
        public IObservable <SearchResponseMessage> Search(string searchTarget, int timeForResponse)
        {
            return(Observable.Create <SearchResponseMessage>(async observer =>
            {
                var searchSocket = new DatagramSocket();

                // Handling responses from found devices
                searchSocket.MessageReceived += async(sender, args) =>
                {
                    var dataReader = args.GetDataReader();
                    dataReader.InputStreamOptions = InputStreamOptions.Partial;

                    if (dataReader.UnconsumedBufferLength == 0)
                    {
                        await dataReader.LoadAsync(1024);
                    }

                    var message = dataReader.ReadString(dataReader.UnconsumedBufferLength);

                    try
                    {
                        var response = SearchResponseMessage.Create(message);

                        observer.OnNext(response);
                    }
                    catch (ArgumentException ex)
                    {
                        logger.Instance().Warning(ex, "The received M-Search response has been ignored.", "Message".As(message));
                    }
                };

                await searchSocket.BindServiceNameAsync("0");
                searchSocket.JoinMulticastGroup(this.multicastHost);

                var request = MSearchRequestFormattedString.F(searchTarget, timeForResponse);
                var buffer = Encoding.UTF8.GetBytes(request).AsBuffer();

                // Sending the search request to a multicast group
                var outputStream = await searchSocket.GetOutputStreamAsync(this.multicastHost, MulticastPort.ToString());
                await outputStream.WriteAsync(buffer);
                await outputStream.WriteAsync(buffer);

                // Stop listening for a devices when timeout for responses is expired
                Observable.Timer(TimeSpan.FromSeconds(timeForResponse)).Subscribe(s =>
                {
                    observer.OnCompleted();
                    searchSocket.Dispose();
                });

                logger.Instance().Debug("M-Search request has been sent. [multicastHost={0}, searchTarget={1}]".F(multicastHost.DisplayName, searchTarget));
                return searchSocket.Dispose;
            }));
        }
예제 #16
0
        /// <summary>
        /// Returns list of bridge IPs
        /// </summary>
        /// <returns></returns>
        public async Task <IEnumerable <LocatedBridge> > LocateBridgesAsync(TimeSpan timeout)
        {
            if (timeout <= TimeSpan.Zero)
            {
                throw new ArgumentException("Timeout value must be greater than zero.", nameof(timeout));
            }

            var discoveredDevices = new List <string>();
            var multicastIP       = new HostName("239.255.255.250");

            using (var socket = new DatagramSocket())
            {
                //Handle MessageReceived
                socket.MessageReceived += (sender, e) =>
                {
                    var reader         = e.GetDataReader();
                    var bytesRemaining = reader.UnconsumedBufferLength;
                    var receivedString = reader.ReadString(bytesRemaining);

                    var location = receivedString.Substring(receivedString.IndexOf("LOCATION:", System.StringComparison.Ordinal) + 9);
                    receivedString = location.Substring(0, location.IndexOf("\r", System.StringComparison.Ordinal)).Trim();

                    discoveredDevices.Add(receivedString);
                };

                await socket.BindEndpointAsync(null, string.Empty);

                socket.JoinMulticastGroup(multicastIP);

                var start = DateTime.Now;

                do
                {
                    using (var stream = await socket.GetOutputStreamAsync(multicastIP, "1900"))
                        using (var writer = new DataWriter(stream))
                        {
                            string request = "M-SEARCH * HTTP/1.1\r\n" +
                                             "HOST:239.255.255.250:1900\r\n" +
                                             //"ST:urn:schemas-upnp-org:device:Basic:1\r\n" + //Alternative
                                             // "ST:upnp:rootdevice\r\n" +                    //Alternative
                                             "ST:SsdpSearch:all\r\n" +
                                             "MAN:\"ssdp:discover\"\r\n" +
                                             "MX:3\r\n\r\n\r\n";

                            writer.WriteString(request.ToString());
                            await writer.StoreAsync();
                        }
                }while (DateTime.Now.Subtract(start) < timeout); // try for thee seconds
            }

            return(await FilterBridges(discoveredDevices));
        }
예제 #17
0
        public void MulticastAddMembership(string ipLan, string mcastAddress)
        {
            if (!_isUnicastInitialized)
            {
                throw new ArgumentException("Multicast interface must be initialized before adding multicast memberships");
            }

            var hostName = new HostName(mcastAddress);

            DatagramSocket.JoinMulticastGroup(hostName);

            _multicastMemberships.Add(mcastAddress, true);
        }
예제 #18
0
        public bool Bind(int port)
        {
            _datagramSocket = new DatagramSocket();
            _datagramSocket.Control.InboundBufferSizeInBytes = NetConstants.SocketBufferSize;
            _datagramSocket.Control.DontFragment             = true;
            _datagramSocket.Control.OutboundUnicastHopLimit  = NetConstants.SocketTTL;
            _datagramSocket.MessageReceived += OnMessageReceived;

            try
            {
                _datagramSocket.BindServiceNameAsync(port.ToString()).AsTask().Wait();
                _datagramSocket.JoinMulticastGroup(MulticastAddressV4);
                _datagramSocket.JoinMulticastGroup(MulticastAddressV6);
                _localEndPoint = new NetEndPoint(_datagramSocket.Information.LocalAddress, _datagramSocket.Information.LocalPort);
            }
            catch (Exception ex)
            {
                NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString());
                return(false);
            }
            return(true);
        }
예제 #19
0
        public async Task Bind(string localAddress, string multicastAddress, string multicastPort)
        {
            information = new ServerInformation(localAddress, multicastAddress, multicastPort);

            socket = new DatagramSocket();
            socket.Control.MulticastOnly = true;

            await socket.BindEndpointAsync(new HostName(information.LocalAddress), information.MulticastPort);

            socket.JoinMulticastGroup(new HostName(information.MulticastAddress));

            socket.MessageReceived += OnMessageReceived;
        }
예제 #20
0
        private static async Task OpenSharedChannelAsync()
        {
            await _mutex.WaitAsync().ConfigureAwait(false);

            if (IsJoined || !_shouldJoinChannel)
            {
                return;
            }

            CloseSharedChannel();

            _log.Info("Opening shared MDNS channel...");

            while (!IsJoined && _shouldJoinChannel)
            {
                try
                {
                    // Create new socket
                    _udpSocket = new DatagramSocket();
                    _udpSocket.MessageReceived += UDPSocket_MessageReceived;

                    // Bind the service name and join the multicast group
                    _log.Debug("Opening UDP socket...");
                    await _udpSocket.BindServiceNameAsync(BonjourUtility.MulticastDNSPort.ToString()).AsTask().ConfigureAwait(false);

                    _log.Debug("Joining multicast group...");
                    _udpSocket.JoinMulticastGroup(_mdnsHostName);

                    // All done
                    IsJoined = true;
                }
                catch (Exception e)
                {
                    _log.Warning("Caught exception while opening UDP socket");
                    _log.Debug("Exception details: " + e.ToString());
                    CloseSharedChannel();
                }

                if (!IsJoined)
                {
                    await Task.Delay(1000).ConfigureAwait(false);
                }
                else
                {
                    _log.Info("Successfully opened shared MDNS channel.");
                }
            }


            _mutex.Release();
        }
예제 #21
0
        public static async void StartListening()
        {
            if (DatagramSocket != null)
            {
                await DatagramSocket.CancelIOAsync();
            }
            DatagramSocket = new DatagramSocket();
            DatagramSocket.MessageReceived += async(sender, args) =>
            {
                await OnReceived(args.GetDataStream(), args.RemoteAddress);
            };
            await DatagramSocket.BindServiceNameAsync(DeviceAuthPort.ToString());

            DatagramSocket.JoinMulticastGroup(DeviceMulticastGroupAddress);
        }
예제 #22
0
        private async Task <DatagramSocket> StartMulticastListenerAsync(string port)
        {
            if (socketIsConnected)
            {
                return(socket);
            }

            socket = new DatagramSocket();
            // You must register handlers before calling BindXxxAsync
            socket.MessageReceived += SocketOnMessageReceived;
            await socket.BindServiceNameAsync(port, NetworkInformation.GetInternetConnectionProfile().NetworkAdapter); // Listen on desired port

            socket.JoinMulticastGroup(multicastIP);                                                                    // Join socket to the multicast IP address
            socketIsConnected = true;
            return(socket);
        }
예제 #23
0
        /// <summary>
        /// Search one device on the local network with the specified name.
        /// </summary>
        /// <param name="deviceName">Friendly name of the device.</param>
        /// <param name="timeoutMiliseconds">Timeout to search the device.</param>
        /// <returns>Device with the specified name.</returns>
        public static async Task <IDeviceInfo> GetDevice(string deviceName, uint timeoutMiliseconds = 6000)
        {
            if (string.IsNullOrEmpty(deviceName))
            {
                throw new ArgumentNullException("deviceName");
            }
            if (timeoutMiliseconds == 0)
            {
                throw new InvalidOperationException("Timeout must be greater than zero.");
            }
            IDeviceInfo deviceInfo = null;
            var         timeoutCancellationTokenSource = new CancellationTokenSource();

            using (var socket = new DatagramSocket())
            {
                socket.MessageReceived += async(sender, args) =>
                {
                    var reader            = args.GetDataReader();
                    var deviceLocationUri = GetDeviceLocation(reader.ReadString(reader.UnconsumedBufferLength));
                    var dinfo             = await GetDeviceInfo(deviceLocationUri);

#if DEBUG
                    Debug.WriteLine(string.Format("DEVICE FOUND: Name = {0}, Manufacturer = {1}, Model = {2}, Address = {3}", dinfo.FriendlyName, dinfo.Manufacturer, dinfo.Model, dinfo.UrlBase));
#endif
                    if (dinfo.FriendlyName.Equals(deviceName))
                    {
                        deviceInfo = dinfo;
                        timeoutCancellationTokenSource.Cancel();
                    }
                };
                await socket.BindEndpointAsync(null, "");

                socket.JoinMulticastGroup(DialConstants.MulticastHost);
                var writer = new DataWriter(await socket.GetOutputStreamAsync(DialConstants.MulticastHost, DialConstants.UdpPort));
                writer.WriteString(string.Format(DialConstants.MSearchMessage, DialConstants.MulticastHost, DialConstants.UdpPort));
                await writer.StoreAsync();

                try
                {
                    await Task.Delay((int)timeoutMiliseconds, timeoutCancellationTokenSource.Token);
                }
                catch
                {}
            }

            return(deviceInfo);
        }
예제 #24
0
        public async override void StartServer(string address, int port)
        {
            try
            {
                socket_ = new DatagramSocket();
                socket_.MessageReceived += OnMessage;

                rcvHost = new HostName(address);
                await socket_.BindServiceNameAsync(port.ToString());

                socket_.JoinMulticastGroup(rcvHost);//この辺でjoinする
            }
            catch (Exception e)
            {
                Debug.LogError(e.ToString());
            }
        }
예제 #25
0
        /// <summary>
        /// Start listening.
        /// </summary>
        public override async Task <bool> StartListeningAsync()
        {
            bool status = false;

            if (_listenerSocket == null)
            {
                _listenerSocket = new DatagramSocket();
                _listenerSocket.MessageReceived += AdvertisementMessageReceivedFromManagerAsync;
                await _listenerSocket.BindServiceNameAsync(ListenerPort);

                _listenerSocket.JoinMulticastGroup(ListenerGroupHost);

                status = true;
            }

            return(status);
        }
예제 #26
0
        // listen for announcements on a given adapter
        Task ListenForAnnouncementsAsync(NetworkAdapter adapter, Action <AdapterInformation, string, byte[]> callback, CancellationToken cancellationToken)
        {
            return(Task.Factory.StartNew(async() =>
            {
                using (var socket = new DatagramSocket())
                {
                    // setup delegate to detach from later
                    TypedEventHandler <DatagramSocket, DatagramSocketMessageReceivedEventArgs> handler =
                        (sock, args) =>
                    {
                        var dr = args.GetDataReader();
                        var buffer = dr.ReadBuffer(dr.UnconsumedBufferLength).ToArray();

                        callback(new AdapterInformation(args.LocalAddress.CanonicalName.ToString(), args.LocalAddress.RawName.ToString()), args.RemoteAddress.RawName.ToString(), buffer);
                    };

                    socket.MessageReceived += handler;

                    // Set control option for multicast. This enables re-use of the port, which is always in use under Windows 10 otherwise.
                    socket.Control.MulticastOnly = true;

                    if (adapter != null)
                    {
                        await socket.BindServiceNameAsync("5353", adapter)
                        .AsTask(cancellationToken)
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        await socket.BindServiceNameAsync("5353")
                        .AsTask(cancellationToken)
                        .ConfigureAwait(false);
                    }

                    socket.JoinMulticastGroup(new HostName("224.0.0.251"));

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        await Task.Delay(5000, cancellationToken).ConfigureAwait(false);
                    }
                    socket.MessageReceived -= handler;
                    socket.Dispose();
                }
            }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap());
        }
예제 #27
0
        /// <summary>
        /// @see http://www.johnthom.com/implementing-ssdp-search-in-windows-phone-8-using-winrt/
        /// </summary>
        public async Task DiscoverDevices()
        {
            int timeout          = 3000;
            var remoteIp         = "239.255.255.250";
            var remoteIpHostName = new Windows.Networking.HostName(remoteIp);
            var port             = "1900";

            string query = "M-SEARCH * HTTP/1.1\r\n" +
                           "HOST: 239.255.255.250:1900\r\n" +
                           "ST: upnp:rootdevice\r\n" +
                           "MAN: \"ssdp:discover\"\r\n" +
                           "MX: " + timeout.ToString() + "\r\n\r\n";

            var buffer = Encoding.UTF8.GetBytes(query);

            using (var socket = new DatagramSocket())
            {
                socket.MessageReceived += (sender, args) => {
                    Task.Run(() => {
                        using (var reader = args.GetDataReader())
                        {
                            byte[] respBuff = new byte[reader.UnconsumedBufferLength];
                            reader.ReadBytes(respBuff);
                            string response = Encoding.UTF8.GetString(respBuff, 0, respBuff.Length).ToLower();
                            response.Trim('\0');

                            ProcessSSDPResponse(response);
                        }
                    });
                };

                await socket.BindEndpointAsync(null, "");

                socket.JoinMulticastGroup(remoteIpHostName);

                using (var stream = await socket.GetOutputStreamAsync(remoteIpHostName, port))
                {
                    await stream.WriteAsync(buffer.AsBuffer());
                }

                // Execute within timeout
                await Task.Delay(timeout);
            }
        }
예제 #28
0
        public async void FindTvs()
        {
            if (searchState == SearchState.Searching)
            {
                StopSearching();
            }

            tvSearchSocket = new DatagramSocket();
            tvSearchSocket.MessageReceived += TvListenCompleted;
            await tvSearchSocket.BindEndpointAsync(null, "");

            tvSearchSocket.JoinMulticastGroup(multicastAddress);
            StartedSearching();
            SendSSDP();

            tvSearchRetryTimer   = new Timer(TvSearchRetry, null, TimeSpan.FromSeconds(tvSearchRetryTimeSeconds), TimeSpan.FromMilliseconds(-1));
            tvSearchTimeoutTimer = new Timer(TvSearchTimeout, null, TimeSpan.FromSeconds(tvSearchTotalTimeSeconds), TimeSpan.FromMilliseconds(-1));

            searchState = SearchState.Searching;
        }
예제 #29
0
        public override async void Start()
        {
            if (Status == ListenerStatus.Listening)
            {
                return;
            }
            try
            {
                _datagramSocket = new DatagramSocket();
                _datagramSocket.MessageReceived += DatagramSocketOnMessageReceived;
                await _datagramSocket.BindServiceNameAsync(MulticastPort.ToString());

                _datagramSocket.JoinMulticastGroup(MulticastIpAddress);
                RaiseStatusChanged(ListenerStatus.Listening);
            }
            catch
            {
                RaiseStatusChanged(ListenerStatus.PortNotFree);
            }
        }
예제 #30
0
        private static async Task BindToSocketAndWriteQuery(DatagramSocket socket, byte[] bytes, CancellationToken cancellationToken)
        {
#if !WINDOWS_PHONE
            try
            {
                // Try to bind using port 5353 first
                await socket.BindServiceNameAsync("5353", NetworkInformation.GetInternetConnectionProfile().NetworkAdapter)
                .AsTask(cancellationToken)
                .ConfigureAwait(false);
            }
            catch (Exception)
            {
                // If it fails, use the default
                await socket.BindServiceNameAsync("", NetworkInformation.GetInternetConnectionProfile().NetworkAdapter)
                .AsTask(cancellationToken)
                .ConfigureAwait(false);
            }
#else
            await socket.BindServiceNameAsync("5353")
            .AsTask(cancellationToken)
            .ConfigureAwait(false);
#endif


            socket.JoinMulticastGroup(new HostName("224.0.0.251"));
            var os = await socket.GetOutputStreamAsync(new HostName("224.0.0.251"), "5353")
                     .AsTask(cancellationToken)
                     .ConfigureAwait(false);

            using (var writer = new DataWriter(os))
            {
                writer.WriteBytes(bytes);
                await writer.StoreAsync()
                .AsTask(cancellationToken)
                .ConfigureAwait(false);

                Debug.WriteLine("Sent mDNS query");

                writer.DetachStream();
            }
        }
예제 #31
0
        public bool Bind(int port)
        {
            _datagramSocket = new DatagramSocket();
            _datagramSocket.Control.InboundBufferSizeInBytes = NetConstants.SocketBufferSize;
            _datagramSocket.Control.DontFragment = true;
            _datagramSocket.Control.OutboundUnicastHopLimit = NetConstants.SocketTTL;
            _datagramSocket.MessageReceived += OnMessageReceived;

            try
            {
                _datagramSocket.BindServiceNameAsync(port.ToString()).AsTask().Wait();
                _datagramSocket.JoinMulticastGroup(MulticastAddressV6);
                _localEndPoint = new NetEndPoint(_datagramSocket.Information.LocalAddress, _datagramSocket.Information.LocalPort);
            }
            catch (Exception ex)
            {
                NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString());
                return false;
            }
            return true;
        }