当前位置: 首页>>代码示例>>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;未经允许,请勿转载。