當前位置: 首頁>>代碼示例>>C#>>正文


C# Sockets.DatagramSocket類代碼示例

本文整理匯總了C#中Windows.Networking.Sockets.DatagramSocket的典型用法代碼示例。如果您正苦於以下問題:C# DatagramSocket類的具體用法?C# DatagramSocket怎麽用?C# DatagramSocket使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


DatagramSocket類屬於Windows.Networking.Sockets命名空間,在下文中一共展示了DatagramSocket類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: LightwaveUwpController

 public LightwaveUwpController(string ipAddress)
 {
     this.IpAddress = ipAddress;
     this.socket = new DatagramSocket();
     ConnectionInProgress = false;
     _registerAttempts = 0;
 }
開發者ID:W1R3D-Code,項目名稱:HomeAutomation,代碼行數:7,代碼來源:LightwaveUwpController.cs

示例2: 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

示例3: GetNetworkTimeAsync

        /// <summary>
        /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
        /// </summary>
        /// <param name="timeout">Operation timeout.</param>
        /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
        public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
        {
            using (var socket = new DatagramSocket())
            using (var ct = new CancellationTokenSource(timeout))
            {
                ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());

                socket.MessageReceived += OnSocketMessageReceived;
                //The UDP port number assigned to NTP is 123
                await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
                using (var writer = new DataWriter(socket.OutputStream))
                {
                    // NTP message size is 16 bytes of the digest (RFC 2030)
                    var ntpBuffer = new byte[48];

                    // Setting the Leap Indicator,
                    // Version Number and Mode values
                    // LI = 0 (no warning)
                    // VN = 3 (IPv4 only)
                    // Mode = 3 (Client Mode)
                    ntpBuffer[0] = 0x1B;

                    writer.WriteBytes(ntpBuffer);
                    await writer.StoreAsync();
                    var result = await _resultCompletionSource.Task;
                    return result;
                }
            }
        }
開發者ID:bajirav,項目名稱:TFAmvvm,代碼行數:34,代碼來源:Ntp.cs

示例4: DoesAThing

    public async void DoesAThing()
    {
      var hostName = new HostName("stun.l.google.com");
      var port = 19302;
      var taskCompletionSource = new TaskCompletionSource<StunUri>();
      using (var datagramSocket = new DatagramSocket())
      {
        datagramSocket.MessageReceived += async (sender, e) =>
        {
          var buffer = await e.GetDataStream().ReadAsync(null, 100, InputStreamOptions.None).AsTask();
          var stunMessage = StunMessage.Parse(buffer.ToArray());
          var xorMappedAddressStunMessageAttribute = stunMessage.Attributes.OfType<XorMappedAddressStunMessageAttribute>().Single();
          taskCompletionSource.SetResult(new StunUri(xorMappedAddressStunMessageAttribute.HostName, xorMappedAddressStunMessageAttribute.Port));
        };

        using (var inMemoryRandomAccessStream = new InMemoryRandomAccessStream())
        {
          var stunMessageId = new StunMessageId(CryptographicBuffer.GenerateRandom(12).ToArray());
          var stunMessageType = StunMessageType.BindingRequest;
          var stunMessageAttributes = new StunMessageAttribute[] { };
          var stunMessage = new StunMessage(stunMessageType, stunMessageAttributes, stunMessageId);
          var bytes = stunMessage.ToLittleEndianByteArray();
          var outputStream = await datagramSocket.GetOutputStreamAsync(hostName, $"{port}");
          var written = await outputStream.WriteAsync(bytes.AsBuffer());
        }
      }

      var result = await taskCompletionSource.Task;
      Assert.AreEqual(result.HostName, new HostName("200.100.50.25"));
      Assert.AreEqual(result.Port, 12345);
    }
開發者ID:Rhaeo,項目名稱:Rhaeo.Stun,代碼行數:31,代碼來源:UnitTest.cs

示例5: SendResponse

        private void SendResponse(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            var controllerSettings = _settingsService.GetSettings<ControllerSettings>();

            var response = new DiscoveryResponse(controllerSettings.Caption, controllerSettings.Description);
            SendResponseAsync(args.RemoteAddress, response).Wait();
        }
開發者ID:chkr1011,項目名稱:CK.HomeAutomation,代碼行數:7,代碼來源:DiscoveryServerService.cs

示例6: SetBackingSocket

        private void SetBackingSocket()
        {
            var socket = new DatagramSocket();
            socket.MessageReceived += DatagramMessageReceived;

            _backingDatagramSocket = socket;
        }
開發者ID:Elecstrap,項目名稱:sockets-for-pcl,代碼行數:7,代碼來源:UdpSocketBase.cs

示例7: datagramSocket_MessageReceived

        async void datagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            i++;
            DataReader dataReader = args.GetDataReader();
            uint length = dataReader.UnconsumedBufferLength;
            string content = dataReader.ReadString(length);
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            msgList.Children.Add(new TextBlock { Text = "服務器收到的消息:" + content }));

            //HostName hostName = new HostName("localhost");
            //DatagramSocket datagramSocket = new DatagramSocket();
            //IOutputStream outputStream = await datagramSocket.GetOutputStreamAsync(hostName, "22112");
            DataWriter writer = new DataWriter(sender.OutputStream);
            writer.WriteString(content + "|" + i);
            try
            {
                await writer.StoreAsync();
                msgList.Children.Add(new TextBlock { Text = "服務器發送的消息:" + content + "|" + i });
            }
            catch (Exception err)
            {
                if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                {

                }
            }
        }
開發者ID:peepo3663,項目名稱:WindowsPhone8,代碼行數:27,代碼來源:MainPage.xaml.cs

示例8: MessageReceived

        private void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            DataReader reader;
            try
            {
                reader = eventArguments.GetDataReader();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("MessageReceived:" + ex);
                return;
            }
            uint dataLength = reader.UnconsumedBufferLength;
            byte[] data = new byte[dataLength];
            reader.ReadBytes(data);

            var packet = new NavigationPacket
            {
                Timestamp = DateTime.UtcNow.Ticks,
                Data = data
            };
            UpdateNavigationData(packet);

            _TimeoutStopWatch.Restart();
        }
開發者ID:napolini,項目名稱:SDK,代碼行數:25,代碼來源:NavDataWorker.cs

示例9: socket_MessageReceived

        void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            DataReader dr = args.GetDataReader();
            var dataLength = dr.UnconsumedBufferLength;

            string discoveryResult = dr.ReadString(dataLength);
            string[] parts = discoveryResult.Split('|');
            string name = parts[0];
            bool isPinProtected = bool.Parse(parts[1]);
            string uniqueName = parts[3];

            var existingTarget = GetShareTarget(uniqueName);

            var discoveredTarget = new ShareTarget()
            {
                Name = name,
                IPAddress = args.RemoteAddress.DisplayName,
                IsPinCodeRequired = isPinProtected,
                ShareTargetUniqueName = uniqueName
            };

            if (existingTarget != null)
            {
                discoveredTarget.ShareCount = existingTarget.ShareCount;
            }

            if (PeerDiscovered != null)
            {
                PeerDiscovered(discoveredTarget);
            }
        }
開發者ID:tomasmcguinness,項目名稱:BeCharming,代碼行數:31,代碼來源:ShareTargetsManager.cs

示例10: 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

示例11: PerformPeerDiscovery

        public async void PerformPeerDiscovery()
        {
            timer.Interval = new TimeSpan(0, 0, 5);
            timer.Start();

            if (socket == null)
            {
                socket = new DatagramSocket();
                socket.MessageReceived += socket_MessageReceived;

                try
                {
                    await socket.BindEndpointAsync(null, "22002");
                }
                catch
                {
                    // Swallow any already bound exceptions!
                }
            }

            using (var outputStream = await socket.GetOutputStreamAsync(new HostName("230.0.0.1"), "22003"))
            {
                using (DataWriter wr = new DataWriter(outputStream))
                {
                    wr.WriteString("**BECHARMING DISCOVERY**");
                    await wr.FlushAsync();
                    await wr.StoreAsync();
                }
            }
        }
開發者ID:tomasmcguinness,項目名稱:BeCharming,代碼行數:30,代碼來源:ShareTargetsManager.cs

示例12: 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

示例13: 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

示例14: 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

示例15: 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


注:本文中的Windows.Networking.Sockets.DatagramSocket類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。