BindServiceNameAsync() public method

public BindServiceNameAsync ( [ localServiceName ) : IAsyncAction
localServiceName [
return IAsyncAction
Beispiel #1
0
        private async void Init()
        {
            _Listener = new DatagramSocket();
            _Listener.MessageReceived += Listener_MessageReceived;

            while (true)
            {
                try
                {
                    await _Listener.BindServiceNameAsync("6");
                    break;
                }
                catch (COMException)
                {
                    var messageDialog = new MessageDialog("Only one usage of each port is normally permitted.\r\n\r\nIs 'Windows IoT Core Watcher' open?", "Port in use");
                    messageDialog.Commands.Add(new UICommand("Try again", (command) => { }));
                    await messageDialog.ShowAsync();
                }
            }

            HostName hostname = new HostName("239.0.0.222");
            _Listener.JoinMulticastGroup(hostname);

            _Settings = ApplicationData.Current.LocalSettings;

            _Timer = new Timer(Timer_Callback, null, 1000, 1000);
        }
Beispiel #2
0
        private async void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            Windows.Networking.Sockets.DatagramSocket socket = new Windows.Networking.Sockets.DatagramSocket();

            socket.MessageReceived += Socket_MessageReceived;

            //You can use any port that is not currently in use already on the machine. We will be using two separate and random
            //ports for the client and server because both the will be running on the same machine.
            string serverPort = "8001";
            string clientPort = "8002";

            //Because we will be running the client and server on the same machine, we will use localhost as the hostname.
            Windows.Networking.HostName serverHost = new Windows.Networking.HostName("127.0.0.1");

            //Bind the socket to the clientPort so that we can start listening for UDP messages from the UDP echo server.
            await socket.BindServiceNameAsync(clientPort);

            await socket.ConnectAsync(serverHost, serverPort);

            //Write a message to the UDP echo server.
            Stream       streamOut = (await socket.GetOutputStreamAsync(serverHost, serverPort)).AsStreamForWrite();
            StreamWriter writer    = new StreamWriter(streamOut);
            string       message   = "I'm the message from client!";
            await writer.WriteLineAsync(message);

            await writer.FlushAsync();
        }
Beispiel #3
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());
			}
		}
Beispiel #4
0
        public override async void Start()
        {
            if (_Started)
                return;
            _SequenceNumber = 1;

            try
            {
                // Connect to the Drone
                udpClient = new DatagramSocket();
                await udpClient.BindServiceNameAsync(_ServiceName);
                await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
                udpWriter = new DataWriter(udpClient.OutputStream);

                udpWriter.WriteByte(1);
                await udpWriter.StoreAsync();

                _Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25));
                _Started = true;
            }
            catch (Exception)
            {
                Stop();
            }
        }
        /// <summary>
        /// Initialize the connection to the network (prepare sockets, join multicast group, handle the right events, etc)
        /// </summary>
        /// <returns></returns>
        public void InitializeSockets()
        {
            if (Initialized)
                return;

            MulticastAddress = new HostName(MulticastAddressStr);
            // To receive packets (either unicast or multicast), a MessageReceived event handler must be defined

            // Initialize the multicast socket and register the event
            MulticastSocket = new DatagramSocket();
            MulticastSocket.MessageReceived += MulticastSocketMessageReceived;

            // bind to a local UDP port
            MulticastSocket.BindServiceNameAsync(MulticastPortStr).AsTask().Wait();

            // Call the JoinMulticastGroup method to join the multicast group.
            MulticastSocket.JoinMulticastGroup(MulticastAddress);

            // Get our IP address
            String MyIPString = PeerConnector.GetMyIP();
            myIPAddress = new HostName(MyIPString);

            // Construct a list of ip addresses that should be ignored
            IgnoreableNetworkAddresses = new List<String> { LinkLocalPrefixString, LocalLoopbackPrefixString, PrivateNetworkPrefixString }; //, MyIPString };
            System.Diagnostics.Debug.WriteLine("Ignored IP Addresses: " + LinkLocalPrefixString + " - " + LocalLoopbackPrefixString + " - " + PrivateNetworkPrefixString);

            TCPListener = new TCPSocketListener("80085", new TCPRequestHandler(ProcessNetworkObject));
            TCPSocketHelper = new TCPSocketClient("80085");
            TCPListener.Start();

            Initialized = true;
        }
        public async Task Open()
        {
            //CheckBackgroundTask();
            //await CheckSocketAsync();

            #region Simple socket creation
            if (listenerSocket == null)
            {
                listenerSocket = new DatagramSocket();
                listenerSocket.Control.DontFragment = true;
                listenerSocket.Control.MulticastOnly = true;
                listenerSocket.MessageReceived += DataReceived;

                try
                {
                    await listenerSocket.BindServiceNameAsync(localService);
                    listenerSocket.JoinMulticastGroup(new HostName(remoteMulticastAddress));
                }
                catch (Exception exception)
                {
                    Close();

                    // If this is an unknown status it means that the error is fatal and retry will likely fail.
                    if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                        throw;

                    //rootPage.NotifyUser("Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage);
                }
            }
            #endregion
        }
 private async Task<DatagramSocket> ListenForTack()
 {
     var socket = new DatagramSocket();
     socket.MessageReceived += Socket_MessageReceived;
     await socket.BindServiceNameAsync(RemoteServiceName);
     Debug.WriteLine("Listening on {0}", RemoteServiceName);
     return socket;
 }
		private async Task ExecuteDiscoveryTask()
		{
			int repeatTime = EndpointController.REPEAT_DISCOVERY_TASK / 2;

			while (running)
			{
				Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Started Cloudlet Discovery using Multicast UDP");
				retry = 0;

				DatagramSocket socketSent = null;
				DatagramSocket socketReplay = null;
				try
				{
					socketSent = new DatagramSocket();
					await socketSent.BindEndpointAsync(null, string.Empty);
					socketSent.JoinMulticastGroup(ip);

					socketReplay = new DatagramSocket();
					socketReplay.MessageReceived += SocketOnMessageReceived;
					await socketReplay.BindServiceNameAsync(replyCloudletPort.ToString());

					using (DataWriter writer = new DataWriter(await socketSent.GetOutputStreamAsync(ip, multicastPort.ToString())))
					{
						while (retry < 60 && running)
						{
							writer.WriteString("mpos_cloudlet_req");
							await writer.StoreAsync();
							await writer.FlushAsync();

							await Task.Delay(500);
							retry++;
						}
					}
				}
				catch (IOException e)
				{
					Debug.WriteLine("## [DiscoveryCloudletMulticast]: Any problem with i/o in multicast system!\n" + e.ToString());
				}
				finally
				{
					socketSent.Dispose();
					socketReplay.Dispose();

					socketSent = null;
					socketReplay = null;
				}

				if (running)
				{
					Debug.WriteLine(">> [DiscoveryCloudletMulticast]: Retry Discovery Cloudlet, in " + repeatTime + " ms");
					await Task.Delay(repeatTime);
				}
				else
				{
					Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Finished Discovery Cloudlet");
				}
			}
		}
Beispiel #9
0
        /// <summary>
        /// Get available Webservices
        /// </summary>
        ///
        internal async Task <int> GetAvailableWSEndpointsInternal()
        {
            int ret = 0;

            try
            {
                this.Status = -2;
                m_endPoints.Clear();

                IsNotWorking = false;

                using (var socket = new Windows.Networking.Sockets.DatagramSocket())
                {
                    // Set the callback for servers' responses
                    //     await m_MessageReceive.WaitAsync();

                    socket.MessageReceived += SocketOnMessageReceived;
                    // Start listening for servers' responses
                    await socket.BindServiceNameAsync(m_ListenPort.ToString());

                    // Send a search message
                    await SendMessage(socket);

                    bool            bTimeOut = false;
                    ThreadPoolTimer timer    = ThreadPoolTimer.CreateTimer((t) =>
                    {
                        bTimeOut = true;
                        m_signal.Release();
                    }, TimeSpan.FromSeconds(m_timeOut + 2)); // Timeout +2
                    await m_signal.WaitAsync();

                    timer.Cancel();
                    timer = null;

                    if (bTimeOut)
                    {
                        ret = -1;
                        await socket.CancelIOAsync();
                    }
                    else
                    {
                        ret = 1;
                    }
                }
            }
            catch (Exception)
            {
                m_signal.Release();
                ret = -1;
            }
            IsNotWorking = true;
            this.Status  = ret;
            return(ret);
        }
        private async Task<DatagramSocket> ListenForTick(NetworkAdapter hostname)
        {
            var socket = new DatagramSocket();
            socket.MessageReceived += OnMessageReceived;

            await socket.BindServiceNameAsync(Settings.RemoteServiceName, hostname);
            socket.JoinMulticastGroup(new HostName(Settings.MulticastAddress));

            Log($"Listening on {hostname.NetworkAdapterId}:{Settings.RemoteServiceName}");

            return socket;
        }
Beispiel #11
0
        public async void StartServer(string port)
        {
            _socket = new DatagramSocket();

            var control = _socket.Control;
            _socket.MessageReceived += OnMessageRecived;
            await _socket.BindServiceNameAsync(port);

            var host = new HostName("192.168.137.1");
            var outputStream = await _socket.GetOutputStreamAsync(host, "8001");
            _writer = new DataWriter(outputStream);

        }
Beispiel #12
0
        public override async void Start()
        {
            udpClient = new DatagramSocket();
         
            // Connect To Drone
            udpClient.MessageReceived += MessageReceived;
            await udpClient.BindServiceNameAsync(_ServiceName);
            await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
            udpWriter = new DataWriter(udpClient.OutputStream);

            SendKeepAliveSignal();
            _TimeoutStopWatch = Stopwatch.StartNew();
        }
        private async Task DoWakeOnLan(string macAddress, string ipAddress, string port)
        {
            var socket = new DatagramSocket();

            await socket.BindServiceNameAsync("0");

            var o = await socket.GetOutputStreamAsync(new HostName(ipAddress), port);
            var writer = new DataWriter(o);
            writer.WriteBytes(GetBuffer(macAddress));
            await writer.StoreAsync();

            socket.Dispose();
        }
 private async Task SendTick()
 {
     using (var socket = new DatagramSocket())
     {
         await socket.BindServiceNameAsync(string.Empty);
         socket.JoinMulticastGroup(new HostName(BroadcastAddress));
         var outputStream =
             await socket.GetOutputStreamAsync(new HostName(BroadcastAddress), RemoteServiceName);
         var buffer = Encoding.UTF8.GetBytes("TT_SEND_DEVICE_INFO");
         await outputStream.WriteAsync(buffer.AsBuffer());
         await outputStream.FlushAsync();
         Debug.WriteLine("TICK Broadcasted to {0}:{1}", BroadcastAddress, RemoteServiceName);
     }
 }
        private async void Search(string st, TimeSpan? timeout = null)
        {
            Log("Search - " + st);

            var ssdp_data = new StringBuilder()
                .Append("M-SEARCH * HTTP/1.1").Append("\r\n")
                .Append("HOST: ").Append(MULTICAST_ADDRESS).Append(":").Append(SSDP_PORT.ToString()).Append("\r\n")
                .Append("MAN: ").Append("\"ssdp:discover\"").Append("\r\n")
                .Append("MX: ").Append(MX.ToString()).Append("\r\n")
                .Append("ST: ").Append(st).Append("\r\n")
                .Append("\r\n")
                .ToString();

            var adapters = TargetNetworkAdapters ?? await GetActiveAdaptersAsync().ConfigureAwait(false);

            await Task.WhenAll(adapters.Select(async adapter =>
            {
                using (var socket = new DatagramSocket())
                {
                    socket.Control.DontFragment = true;
                    socket.MessageReceived += OnDatagramSocketMessageReceived;

                    try
                    {
                        await socket.BindServiceNameAsync("", adapter);

                        using (var output = await socket.GetOutputStreamAsync(MULTICAST_HOST, SSDP_PORT.ToString()))
                        {
                            using (var writer = new DataWriter(output))
                            {
                                writer.WriteString(ssdp_data);
                                await writer.StoreAsync();
                            }
                        }

                        await Task.Delay(timeout ?? DEFAULT_TIMEOUT).ConfigureAwait(false);
                        Log("Search Timeout");
                        await socket.CancelIOAsync();
                    }
                    catch (Exception e)
                    {
                        Log("Failed to send multicast: " + e.StackTrace);
                    }

                    socket.MessageReceived -= OnDatagramSocketMessageReceived;
                }
            })).ConfigureAwait(false);

            Finished?.Invoke(this, new EventArgs());
        }
Beispiel #16
0
        public async void SendMessage()
        {
            socket.MessageReceived += Socket_MessageReceived;

            //You can use any port that is not currently in use already on the machine. We will be using two separate and random
            //ports for the client and server because both the will be running on the same machine.

            //Because we will be running the client and server on the same machine, we will use localhost as the hostname.


            //Bind the socket to the clientPort so that we can start listening for UDP messages from the UDP echo server.
            await socket.BindServiceNameAsync(clientPort);

            //Write a message to the UDP echo server.
        }
        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。Parameter
        /// 属性通常用于配置页。</param>
        async protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 创建一个新的socket实例,并绑定到一个本地端口上
            DatagramSocket udpSocket = new DatagramSocket();
            await udpSocket.BindServiceNameAsync("3721");

            // 打开一个连接到远程主机上
            HostName remoteHost = new HostName("192.168.1.100");
            await udpSocket.ConnectAsync(remoteHost, "3721");

            // 将一个字符串以UDP数据包形式发送到远程主机上
            DataWriter udpWriter = new DataWriter(udpSocket.OutputStream);
            udpWriter.WriteString("这里是破船之家");
            await udpWriter.StoreAsync();
        }
        /// <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;
        }
Beispiel #19
0
 private async void UDPClientReceiver_Init()
 {
     try
     {
         // UDP通信インスタンスの初期化
         p_Socket = new Windows.Networking.Sockets.DatagramSocket();
         // 受信時のコールバック関数を登録する
         p_Socket.MessageReceived += OnMessage;
         // 指定のポートで受信を開始する
         p_Socket.BindServiceNameAsync(UDPReceivePort.ToString());
     }
     catch (System.Exception e)
     {
         Debug.LogError(e.ToString());
     }
 }
        private async void StartClick(object sender, RoutedEventArgs e)
        {
            try
            {
                datagramSocket = new DatagramSocket();
                datagramSocket.MessageReceived += MessageReceived;
                await datagramSocket.BindServiceNameAsync(port.ToString());
                this.OutputString("Done!");
            }
            catch (Exception ex)
            {
                datagramSocket = null;
                this.OutputString(ex.Message);
            }

        }
Beispiel #21
0
	    public async void Start()
	    {
           socket = new DatagramSocket();
           socket.MessageReceived += socket_MessageReceived;

            try
            {
                await socket.BindServiceNameAsync(config.Port.ToString());
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
                Debug.Log(SocketError.GetStatus(e.HResult).ToString());
                return;
            }
	    }
        private async void listener_Click(object sender, RoutedEventArgs e)
        {
            DatagramSocket datagramSocket = new DatagramSocket();
            datagramSocket.MessageReceived += datagramSocket_MessageReceived;
            try
            {
                await datagramSocket.BindServiceNameAsync("22112");
                msgList.Children.Add(new TextBlock { Text = "监听成功" });
            }
            catch (Exception err)
            {
                if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                {

                }
            }
        }
 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);
     }
 }
Beispiel #24
0
        //
        // Constructor
        //
        public DiscoveryServer(DiscoveryMode mode)
        {
            m_mode = mode;
            m_dataSocket = new DatagramSocket();

            // Register for message callbacks. We do this both on the server and client
            // so the client can invoke the server when it comes online.
            m_dataSocket.MessageReceived += DataSocket_MessageRecieved;
            new Task(async () =>
            {
                try
                {
                    await m_dataSocket.BindServiceNameAsync(GLOW_SERVER_DISCOVER_PORT + "");
                }
                catch(Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("UDP unable to bind to port!. Message: " + e.Message);
                }                    
            }).Start();  
        }
 public static IObservable<ZeroconfRecord> Resolve(string protocol)
 {
     return Observable.Create<ZeroconfRecord>(async observer =>
         {
             var socket = new DatagramSocket();
             var s = Observable
                 .FromEventPattern
                 <TypedEventHandler<DatagramSocket, DatagramSocketMessageReceivedEventArgs>,
                     DatagramSocketMessageReceivedEventArgs>(
                         x => socket.MessageReceived += x, _ => socket.Dispose())
                 .Select(ProcessMessage)
                 .Where(x => x != null)
                 .Subscribe(observer);
             await socket.BindServiceNameAsync("5353");
             socket.JoinMulticastGroup(new HostName("224.0.0.251"));
             var os = await socket.GetOutputStreamAsync(new HostName("224.0.0.251"), "5353");
             var writer = new DataWriter(os);
             WriteQueryMessage(protocol, writer);
             writer.StoreAsync();
             return s;
         });
 }
Beispiel #26
0
        private static async Task BindToSocketAndWriteQuery(DatagramSocket socket, byte[] bytes, CancellationToken cancellationToken)
        {
            await socket.BindServiceNameAsync("5353")
                        .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();
            }
        }
Beispiel #27
0
        public override async void Start()
        {
            if (_Started)
                return;
            _SequenceNumber = 1;

            // Connect To Drone
            udpClient = new DatagramSocket();
            await udpClient.BindServiceNameAsync(_ServiceName);
            await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
            udpWriter = new DataWriter(udpClient.OutputStream);

            //string path = string.Format("AR.Drone-CommandHistory_{0:yyyy-MM-dd-HH-mm}.txt", DateTime.Now);
            //commandHistoryFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);
            // Write first message
            //byte[] firstMessage = BitConverter.GetBytes(1);
            //WriteString(firstMessage.ToString());

            udpWriter.WriteByte(1);
            await udpWriter.StoreAsync();

            _Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25));
            _Started = true;
        }
        /// <summary>
        /// This is the click handler for the 'StartListener' button.
        /// </summary>
        /// <param name="sender">Object for which the event was generated.</param>
        /// <param name="e">Event's parameters.</param>
        private async void StartListener_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(ServiceName.Text))
            {
                rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage);
                return;
            }

            if (listenerSocket != null)
            {
                rootPage.NotifyUser("A listener socket is already set up.", NotifyType.ErrorMessage);
                return;
            }

            bool isMulticastSocket = (MulticastRadioButton.IsChecked == true);
            listenerSocket = new DatagramSocket();
            listenerSocket.MessageReceived += MessageReceived;

            if (isMulticastSocket)
            {
                // DatagramSockets conduct exclusive (SO_EXCLUSIVEADDRUSE) binds by default, effectively blocking
                // any other UDP socket on the system from binding to the same local port. This is done to prevent
                // other applications from eavesdropping or hijacking a DatagramSocket's unicast traffic.
                //
                // Setting the MulticastOnly control option to 'true' enables a DatagramSocket instance to share its
                // local port with any Win32 sockets that are bound using SO_REUSEADDR/SO_REUSE_MULTICASTPORT and
                // with any other DatagramSocket instances that have MulticastOnly set to true. However, note that any
                // attempt to use a multicast-only DatagramSocket instance to send or receive unicast data will result
                // in an exception being thrown.
                //
                // This control option is particularly useful when implementing a well-known multicast-based protocol,
                // such as mDNS and UPnP, since it enables a DatagramSocket instance to coexist with other applications
                // running on the system that also implement that protocol.
                listenerSocket.Control.MulticastOnly = true;
            }

            // Start listen operation.
            try
            {
                await listenerSocket.BindServiceNameAsync(ServiceName.Text);

                if (isMulticastSocket)
                {
                    // Join the multicast group to start receiving datagrams being sent to that group.
                    listenerSocket.JoinMulticastGroup(new HostName(RemoteAddress.Text));

                    rootPage.NotifyUser(
                        "Listening on port " + listenerSocket.Information.LocalPort + " and joined to multicast group",
                        NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser(
                        "Listening on port " + listenerSocket.Information.LocalPort,
                        NotifyType.StatusMessage);
                }

                // Enable scenario steps that require us to have an active listening socket.
                SendMessageButton.IsEnabled = true;
                CloseListenerButton.IsEnabled = true;
            }
            catch (Exception exception)
            {
                listenerSocket.Dispose();
                listenerSocket = null;

                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                rootPage.NotifyUser(
                    "Start listening failed with error: " + exception.Message,
                    NotifyType.ErrorMessage);
            }
        }
        /// <summary>
        /// This is the click handler for the 'StartListener' button.
        /// </summary>
        /// <param name="sender">Object for which the event was generated.</param>
        /// <param name="e">Event's parameters.</param>
        private async void StartListener_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(ServiceNameForListener.Text))
            {
                rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage);
                return;
            }

            if (CoreApplication.Properties.ContainsKey("listener"))
            {
                rootPage.NotifyUser(
                    "This step has already been executed. Please move to the next one.", 
                    NotifyType.ErrorMessage);
                return;
            }

            CoreApplication.Properties.Remove("serverAddress");

            DatagramSocket listener = new DatagramSocket();
            listener.MessageReceived += MessageReceived;

            if (!String.IsNullOrWhiteSpace(InboundBufferSize.Text))
            {
                uint inboundBufferSize = 0;
                if (!uint.TryParse(InboundBufferSize.Text, out inboundBufferSize))
                {
                    rootPage.NotifyUser(
                        "Please provide a positive numeric Inbound buffer size.", 
                        NotifyType.ErrorMessage);
                    return;
                }

                try
                {
                    // Running both client and server on localhost will most likely not reach the buffer limit.
                    // Refer to the DatagramSocketControl class' MSDN documentation for the full list of control options.
                    listener.Control.InboundBufferSizeInBytes = inboundBufferSize;
                }
                catch (ArgumentException)
                {
                    rootPage.NotifyUser("Please provide a valid Inbound buffer size.", NotifyType.ErrorMessage);
                    return;
                }
            }

            LocalHostItem selectedLocalHost = null; 
            if ((BindToAddress.IsChecked == true) || (BindToAdapter.IsChecked == true))
            {
                selectedLocalHost = (LocalHostItem)AdapterList.SelectedItem;
                if (selectedLocalHost == null)
                {
                    rootPage.NotifyUser("Please select an address / adapter.", NotifyType.ErrorMessage);
                    return;
                }

                // The user selected an address. For demo purposes, we ensure that connect will be using the same 
                // address.
                CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName);
            }

            // Save the socket, so subsequent steps can use it.
            CoreApplication.Properties.Add("listener", listener);

            // Start listen operation.
            try
            {
                if (BindToAny.IsChecked == true)
                {
                    // Don't limit traffic to an address or an adapter.
                    await listener.BindServiceNameAsync(ServiceNameForListener.Text);
                    rootPage.NotifyUser("Listening", NotifyType.StatusMessage);
                }
                else if (BindToAddress.IsChecked == true)
                {
                    // Try to bind to a specific address.
                    await listener.BindEndpointAsync(selectedLocalHost.LocalHost, ServiceNameForListener.Text);
                    rootPage.NotifyUser(
                        "Listening on address " + selectedLocalHost.LocalHost.CanonicalName, 
                        NotifyType.StatusMessage);
                }
                else if (BindToAdapter.IsChecked == true)
                {
                    // Try to limit traffic to the selected adapter. 
                    // This option will be overriden by interfaces with weak-host or forwarding modes enabled.
                    NetworkAdapter selectedAdapter = selectedLocalHost.LocalHost.IPInformation.NetworkAdapter;

                    await listener.BindServiceNameAsync(ServiceNameForListener.Text, selectedAdapter);

                    rootPage.NotifyUser(
                        "Listening on adapter " + selectedAdapter.NetworkAdapterId, 
                        NotifyType.StatusMessage);
                }
            }
            catch (Exception exception)
            {
                CoreApplication.Properties.Remove("listener");
                
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                rootPage.NotifyUser(
                    "Start listening failed with error: " + exception.Message, 
                    NotifyType.ErrorMessage);
            }
        }
        /// <summary>
        /// Creates a new UDP socket and starts advertising the AdvertisingMessage to the AdvertiserPort and AdvertiserGroupHost
        /// </summary>
        public override async Task<bool> StartAdvertisingAsync()
        {
            bool status = false;

            if (AdvertiserSocket == null)
            {
                AdvertiserSocket = new DatagramSocket();

                // Attach event handler and start listening on given port.
                AdvertiserSocket.MessageReceived += MessageToConnectReceivedFromParticipantAsync;
                await AdvertiserSocket.BindServiceNameAsync(AdvertiserPort);

                // Start the timer, to send a message every X milliseconds.
                _timer = new Timer(async state => await SendMessageAsync(), null, 0, AdvertiserInterval);

                status = true;
            }

            return status;
        }
Beispiel #31
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();
            }
        }
        private async void StartListener_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(ServiceNameForListener.Text))
            {
                _rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage);
                return;
            }

            if (CoreApplication.Properties.ContainsKey("listener"))
            {
                _rootPage.NotifyUser(
                    "This step has already been executed. Please move to the next one.",
                    NotifyType.ErrorMessage);
                return;
            }

            CoreApplication.Properties.Remove("serverAddress");

            // サーバソケットの作成
            var listener = new Windows.Networking.Sockets.DatagramSocket();

            // メッセージを受信したときのハンドラ
            listener.MessageReceived += MessageReceivedAsync;

            if (!string.IsNullOrWhiteSpace(InboundBufferSize.Text))
            {
                if (!uint.TryParse(InboundBufferSize.Text, out var inboundBufferSize))
                {
                    _rootPage.NotifyUser(
                        "Please provide a positive numeric Inbound buffer size.",
                        NotifyType.ErrorMessage);
                    return;
                }

                try
                {
                    // 受信時のデータバッファサイズをセット
                    listener.Control.InboundBufferSizeInBytes = inboundBufferSize;
                }
                catch (ArgumentException)
                {
                    _rootPage.NotifyUser("Please provide a valid Inbound buffer size.", NotifyType.ErrorMessage);
                    return;
                }
            }

            // Address or Adapter binding
            LocalHostItem selectedLocalHost = null;

            if ((BindToAddress.IsChecked == true) || (BindToAdapter.IsChecked == true))
            {
                selectedLocalHost = (LocalHostItem)AdapterList.SelectedItem;
                if (selectedLocalHost == null)
                {
                    _rootPage.NotifyUser("Please select an address / adapter.", NotifyType.ErrorMessage);
                    return;
                }

                CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName);
            }

            // 作成したソケットをアプリに保存する
            CoreApplication.Properties.Add("listener", listener);

            // Listenの開始
            try
            {
                if (BindToAny.IsChecked == true)
                {
                    // コントロールに入力されたポートでListenする
                    await listener.BindServiceNameAsync(ServiceNameForListener.Text);

                    _rootPage.NotifyUser("Listening", NotifyType.StatusMessage);
                }
                else if (BindToAddress.IsChecked == true)
                {
                    if (selectedLocalHost == null)
                    {
                        return;
                    }
                    await listener.BindEndpointAsync(selectedLocalHost.LocalHost, ServiceNameForListener.Text);

                    _rootPage.NotifyUser(
                        "Listening on addrress " + selectedLocalHost.LocalHost.CanonicalName,
                        NotifyType.StatusMessage);
                }
                else if (BindToAdapter.IsChecked == true)
                {
                    if (selectedLocalHost == null)
                    {
                        return;
                    }
                    var selectedAdapter = selectedLocalHost.LocalHost.IPInformation.NetworkAdapter;

                    await listener.BindServiceNameAsync(ServiceNameForListener.Text, selectedAdapter);

                    _rootPage.NotifyUser(
                        "Listening on adapter " + selectedAdapter.NetworkAdapterId,
                        NotifyType.StatusMessage);
                }
            }
            catch (Exception exception)
            {
                CoreApplication.Properties.Remove("listenner");
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                _rootPage.NotifyUser(
                    "Start listening failed with error: " + exception.Message,
                    NotifyType.ErrorMessage);
            }
        }
Beispiel #33
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;
			});
		}
Beispiel #34
0
        private async void ConnectUdpReceive_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                if (receiveSocket == null)
                {
                    receiveSocket = new DatagramSocket();

                    // MessageReceived handler must be set before BindServiceAsync is called, if not
                    // "A method was called at an unexpected time. (Exception from HRESULT: 
                    // 0x8000000E)" exception is thrown.
                    receiveSocket.MessageReceived += OnMessageReceived;

                    // If port is already in used by another socket, "Only one usage of each socket
                    // address (protocol/network address/port) is normally permitted. (Exception from
                    // HRESULT: 0x80072740)" exception is thrown.
                    await receiveSocket.BindServiceNameAsync("2704");

                    DisplayOutput(UdpReceiveOutput, "Connected (bound).");
                }
            }
            catch (Exception ex)
            {
                DisplayOutput(UdpReceiveOutput, ex.ToString());
            }
        }
Beispiel #35
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;
        }