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