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


C# Networking.HostName類代碼示例

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


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

示例1: Connect

        public async Task<bool> Connect()
        {
            if (_connected) return false;
            var hostname = new HostName("62.4.24.188");
            //var hostname = new HostName("192.168.1.12");
            CancellationTokenSource cts = new CancellationTokenSource();
            try
            {
                cts.CancelAfter(5000);
                await _clientSocket.ConnectAsync(hostname, "4242").AsTask(cts.Token);
            }
            catch (TaskCanceledException)
            {
                _connected = false;
                return false;
            }
            _connected = true;
            _dataReader = new DataReader(_clientSocket.InputStream)
            {
                InputStreamOptions = InputStreamOptions.Partial
            };
            ReadData();
            return true;

        }
開發者ID:patel-pragnesh,項目名稱:PowerMonitor,代碼行數:25,代碼來源:Socket.cs

示例2: connect

 //Connects to server
 public async Task connect(string address, int port)
 {
     if (!this.connected)
     {
         try
         {
             this.socket = new StreamSocket();
             this.hostname = new HostName(address);
             this.port = port;
             await this.socket.ConnectAsync(this.hostname, port.ToString());
             this.writer = new DataWriter(this.socket.OutputStream);
             this.reader = new DataReader(this.socket.InputStream);
             this.reader.InputStreamOptions = InputStreamOptions.Partial;
             connected = true;
         }
         catch (Exception e)
         {
             connected = false;
             Debug.WriteLine(e.Message);
         }
     }
     else
     {
         await new MessageDialog("Already connected", "Information").ShowAsync();
         connected = true;
         
     }
 }
開發者ID:HaavardM,項目名稱:havissIoT-WindowsApp,代碼行數:29,代碼來源:HavissIoTClient.cs

示例3: ConnectAsync

        internal async Task ConnectAsync(
            HostName hostName,
            string serviceName,
            string user,
            string password)
        {
            if (controlStreamSocket != null)
            {
                throw new InvalidOperationException("Control connection already started.");
            }

            this.hostName = hostName;

            controlStreamSocket = new StreamSocket();
            await controlStreamSocket.ConnectAsync(hostName, serviceName);

            reader = new DataReader(controlStreamSocket.InputStream);
            reader.InputStreamOptions = InputStreamOptions.Partial;

            writer = new DataWriter(controlStreamSocket.OutputStream);

            readCommands = new List<string>();
            loadCompleteEvent = new AutoResetEvent(false);
            readTask = InfiniteReadAsync();

            FtpResponse response;
            response = await GetResponseAsync();
            VerifyResponse(response, 220);

            response = await UserAsync(user);
            VerifyResponse(response, 331);

            response = await PassAsync(password);
            VerifyResponse(response, 230);
        }
開發者ID:kiewic,項目名稱:FtpClient,代碼行數:35,代碼來源:FtpClient.cs

示例4: Settings

 public Settings()
 {
     socket = new StreamSocket();
     ConnectToServer();
     host = new HostName("192.168.12.171");
     this.InitializeComponent();
 }
開發者ID:orenafek,項目名稱:AirHockey,代碼行數:7,代碼來源:Settings.xaml.cs

示例5: ConnectAsyncInternal

        private async Task ConnectAsyncInternal(HostName hostName)
        {
            _tokenSource = new CancellationTokenSource();

            _socket = new StreamSocket();

            // połącz z kontrolerem na porcie 5555 
            await _socket.ConnectAsync(hostName, "5555", SocketProtectionLevel.PlainSocket);

            // wyslij komendę odblokowującą
            await _socket.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(UnlockCommand).AsBuffer());

            // read the "Accept:EV340\r\n\r\n" response
            //stworzenie bufor na odpowiedź
            IBuffer bufferResponse = new Buffer(128);
            //pobranie do bufora odpowiedzi przychodzącej od kontrolera EV3
            await _socket.InputStream.ReadAsync(bufferResponse, bufferResponse.Capacity, InputStreamOptions.Partial);
            //przekształcenie danych z bufora na ciag znaków w formacie UTF8
            string response = Encoding.UTF8.GetString(bufferResponse.ToArray(), 0, (int)bufferResponse.Length);
            if (string.IsNullOrEmpty(response))
                //zgłoszenie błędu w razie braku odpowiedzi
                throw new Exception("LEGO EV3 brick did not respond to the unlock command.");
            //rozpoczęcie pobierania danych
            await ThreadPool.RunAsync(PollInput);
        }
開發者ID:BananaScheriff,項目名稱:legoev3,代碼行數:25,代碼來源:NetworkCommunication.cs

示例6: IsReachable

    /// <summary>
    /// Checks if remote is reachable. RT apps cannot do loopback so this will alway return false.
    /// You can use it to check remote calls though.
    /// </summary>
    /// <param name="host"></param>
    /// <param name="msTimeout"></param>
    /// <returns></returns>
    public override async Task<bool> IsReachable(string host, int msTimeout = 5000)
    {
      if (string.IsNullOrEmpty(host))
        throw new ArgumentNullException("host");

      if (!IsConnected)
        return false;


     
      try
      {
        var serverHost = new HostName(host);
        using(var client = new StreamSocket())
        {
          await client.ConnectAsync(serverHost, "http");
          return true;
        }


      }
      catch(Exception ex)
      {
        Debug.WriteLine("Unable to reach: " + host + " Error: " + ex);
        return false;
      }
    }
開發者ID:Lotpath,項目名稱:Xamarin.Plugins,代碼行數:34,代碼來源:ConnectivityImplementation.cs

示例7: ProcessDeviceDiscoveryMessage

		private void ProcessDeviceDiscoveryMessage(HostName remoteAddress, string remotePort, LifxResponse msg)
		{
			if (DiscoveredBulbs.ContainsKey(remoteAddress.ToString()))  //already discovered
            {
				DiscoveredBulbs[remoteAddress.ToString()].LastSeen = DateTime.UtcNow; //Update datestamp
				return;
			}
			if (msg.Source != discoverSourceID || //did we request the discovery?
				_DiscoverCancellationSource == null ||
				_DiscoverCancellationSource.IsCancellationRequested) //did we cancel discovery?
				return;

			var device = new LightBulb()
			{
				HostName = remoteAddress,
				Service = msg.Payload[0],
				Port = BitConverter.ToUInt32(msg.Payload, 1),
				LastSeen = DateTime.UtcNow
			};
			DiscoveredBulbs[remoteAddress.ToString()] = device;
			devices.Add(device);
			if (DeviceDiscovered != null)
			{
				DeviceDiscovered(this, new DeviceDiscoveryEventArgs() { Device = device });
			}
		}
開發者ID:modulexcite,項目名稱:LifxNet,代碼行數:26,代碼來源:LifxClient.Discovery.cs

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

示例9: IPAddress

 public IPAddress(uint value)
 {
     m_addressBytes = IPAddressHelper.GetAddressBytes(value);
     m_value = value;
     m_stringValue = IPAddressHelper.GetAddressString(m_addressBytes);
     m_hostName = new HostName(m_stringValue);
 }
開發者ID:atanasmihaylov,項目名稱:lanscan,代碼行數:7,代碼來源:IPAddress.cs

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

示例11: RemoveRoutePolicy_Click

        private void RemoveRoutePolicy_Click(object sender, RoutedEventArgs e)
        {
            if (rootPage.g_ConnectionSession == null)
            {
                OutputText.Text = "Please establish a connection using the \"Create Connection\" scenario first.";

                return;
            }

            try
            {
                HostName hostName = new HostName(HostName.Text);
                DomainNameType domainNameType = ParseDomainNameType(((ComboBoxItem)DomainNameTypeComboBox.SelectedItem).Content.ToString());
                RoutePolicy routePolicy = new RoutePolicy(rootPage.g_ConnectionSession.ConnectionProfile, hostName, domainNameType);

                Windows.Networking.Connectivity.ConnectivityManager.RemoveHttpRoutePolicy(routePolicy);

                OutputText.Text = "Removed Route Policy\nTraffic to " + routePolicy.HostName.ToString() +
                    " will no longer be routed through " + routePolicy.ConnectionProfile.ProfileName;
            }
            catch (ArgumentException ex)
            {
                OutputText.Text = "Failed to remove Route Policy with HostName = \"" + HostName.Text + "\"\n" +
                    ex.Message;
            }
        }
開發者ID:mbin,項目名稱:Win81App,代碼行數:26,代碼來源:S2_AddRoutePolicy.xaml.cs

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

示例13: SendMessage

 public async void SendMessage(string msg)
 {
     HostName hostName;
     try
     {
         hostName = new HostName("localhost");
     }
     catch (ArgumentException)
     {
         return;
     }
     StreamSocket socket;
     try
     {
         using (socket = new StreamSocket())
         {
             await socket.ConnectAsync(hostName, port2);
             //CoreApplication.Properties.Add("connected", null);
             DataWriter dw = new DataWriter(socket.OutputStream);
             dw.WriteString(msg);
             await dw.StoreAsync();
         }
     }
     catch
     {
         //break;
     }
 }
開發者ID:ballance,項目名稱:MetroTorrent,代碼行數:28,代碼來源:ServerCommunicator.cs

示例14: Connect

        public static void Connect(string address, string port)
        {
            if (!connected)
            {
                clientSocket = new StreamSocket();

                try
                {
                    serverHost = new HostName(address);
                    serverPort = port;
                    serverHostnameString = address;
                    writer = new DataWriter(clientSocket.OutputStream);

                    clientSocket.ConnectAsync(serverHost, serverPort);
                    connected = true;
                }
                catch (Exception)
                {
                    clientSocket.Dispose();
                    clientSocket = null;

                    throw new ConnectionErrorException();
                }
            }
            else
            {
                clientSocket.Dispose();
                clientSocket = null;
                connected = false;

                GamepadClient.Connect(address, port);
            }
        }
開發者ID:GudoshnikovaAnna,項目名稱:qreal,代碼行數:33,代碼來源:SocketClient.cs

示例15: FrameUploader

 public FrameUploader(string id, IPAddress address, int port)
 {
     _host = new HostName(address.ToString());
     _port = port.ToString();
     _cameraId = id;
     UploadComplete = () => { };
 }
開發者ID:joshholmes,項目名稱:BulletTime,代碼行數:7,代碼來源:FrameUploader.cs


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