当前位置: 首页>>代码示例>>C#>>正文


C# DatagramSocket.BindServiceNameAsync方法代码示例

本文整理汇总了C#中Windows.Networking.Sockets.DatagramSocket.BindServiceNameAsync方法的典型用法代码示例。如果您正苦于以下问题:C# DatagramSocket.BindServiceNameAsync方法的具体用法?C# DatagramSocket.BindServiceNameAsync怎么用?C# DatagramSocket.BindServiceNameAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Windows.Networking.Sockets.DatagramSocket的用法示例。


在下文中一共展示了DatagramSocket.BindServiceNameAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Init

        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);
        }
开发者ID:cyberh0me,项目名称:IoT,代码行数:27,代码来源:Discovery.cs

示例2: init

		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());
			}
		}
开发者ID:88to,项目名称:titanium_mobile,代码行数:29,代码来源:Logger.cs

示例3: InitializeSockets

        /// <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;
        }
开发者ID:svdvonde,项目名称:bachelorproef,代码行数:36,代码来源:PeerConnector.cs

示例4: Start

        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();
            }
        }
开发者ID:Eggies,项目名称:SDK,代码行数:25,代码来源:CommandWorker.cs

示例5: Open

        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
        }
开发者ID:KonstantinKolesnik,项目名称:SmartHub,代码行数:31,代码来源:WemosTransport.cs

示例6: ListenForTack

 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;
 }
开发者ID:HouseOfTheFuture,项目名称:Mobile-App,代码行数:8,代码来源:DiscoverService.cs

示例7: ExecuteDiscoveryTask

		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");
				}
			}
		}
开发者ID:sergiosilvajr,项目名称:mpos,代码行数:58,代码来源:DiscoveryCloudletMulticast.cs

示例8: ListenForTick

        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;
        }
开发者ID:HouseOfTheFuture,项目名称:IoT-Device,代码行数:12,代码来源:MainPage.xaml.cs

示例9: StartServer

        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);

        }
开发者ID:Quantzo,项目名称:IotRouter,代码行数:13,代码来源:DatagramServer.cs

示例10: Start

        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();
        }
开发者ID:napolini,项目名称:SDK,代码行数:13,代码来源:NavDataWorker.cs

示例11: DoWakeOnLan

        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();
        }
开发者ID:zardaloop,项目名称:Emby.WindowsPhone,代码行数:13,代码来源:NetworkConnection.cs

示例12: Search

        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());
        }
开发者ID:kazyx,项目名称:kz-ssdp-discovery,代码行数:50,代码来源:SsdpDiscoveryUwp.cs

示例13: SendTick

 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);
     }
 }
开发者ID:HouseOfTheFuture,项目名称:Mobile-App,代码行数:14,代码来源:DiscoverService.cs

示例14: OnNavigatedTo

        /// <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();
        }
开发者ID:BeyondVincent,项目名称:WindowsStoreAppCode,代码行数:20,代码来源:MainPage.xaml.cs

示例15: StartListeningAsync

        /// <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;
        }
开发者ID:Hitchhikrr,项目名称:Windows-appsample-quizgame,代码行数:19,代码来源:UdpParticipant.cs


注:本文中的Windows.Networking.Sockets.DatagramSocket.BindServiceNameAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。