• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Networking.HostName类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



HostName类属于Windows.Networking命名空间,在下文中一共展示了HostName类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: ConnectAsync

    override public async Task ConnectAsync(DeviceInfo RacerDevice)
    {
      try
      {
        //First connect to the bluetooth device...
        HostName deviceHost = new HostName(RacerDevice.HostName);

        //If the socket is already in use, dispose of it
        if (streamSocket != null || dataWriter != null)
          CloseConnection();

        //Create a new socket
        streamSocket = new StreamSocket();
        await streamSocket.ConnectAsync(deviceHost, "1");

        dataWriter = new DataWriter(streamSocket.OutputStream);
        RaisePropertyChanged("IsConnected");
      }
      catch(Exception ex)
      {
        //Dispose and Destroy the StreamSocket and DataWriter
        CloseConnection();

        //Not sure what to do here yet, just pass it along
        throw;
      }
      finally
      {
        //Regardless of what happened, let the view know that the connection state likely changed. 
        RaiseRacerConnectionStateChanged();
      }
    }
开发者ID:BretStateham,项目名称:i-Drive,代码行数:32,代码来源:Racer.cs


示例17: ConnectSocket_Click

 private async void ConnectSocket_Click(object sender, RoutedEventArgs e)
 {
     if (string.IsNullOrEmpty(ServiceNameForConnect.Text))
     {
         rootPage.NotifyUser("请提供服务器名", NotifyType.ErrorMessage);
         return;
     }
     HostName hostName;
     try
     {
         hostName = new HostName(HostNameForConnect.Text);
     }
     catch (ArgumentException)
     {
         rootPage.NotifyUser("错误:无效主机名", NotifyType.ErrorMessage);
         return;
     }
     rootPage.NotifyUser("连接至" + HostNameForConnect.Text, NotifyType.StatusMessage);
     using (StreamSocket socket = new StreamSocket())
     {
         socket.Control.ClientCertificate = null;
         bool shouldRetry = await TryConnectSocketWithRetryAsync(socket, hostName);
         if (shouldRetry)
         {
             await TryConnectSocketWithRetryAsync(socket, hostName);
         }
     }
 }
开发者ID:SongOfSaya,项目名称:MySocket,代码行数:28,代码来源:Scenario5_Certificates.xaml.cs


示例18: SmtpSocket

 /// <summary>
 /// Creates a new instance of SmtpSocket.
 /// </summary>
 /// <param name="server">Server host name.</param>
 /// <param name="port">Port (usually 25).</param>
 /// <param name="ssl">SSL/TLS support.</param>
 public SmtpSocket(string server, int port, bool ssl)
 {
     _host = new HostName(server);
     _socket = new StreamSocket();
     _port = port;
     _ssl = ssl;
 }
开发者ID:AlessandroBo,项目名称:SMTP-WinRT,代码行数:13,代码来源:SmtpSocket.cs


示例19: connect

    public void connect(string args)
    {
        string[] javascriptArgs = JsonHelper.Deserialize<string[]>(args);
        string macAddress = javascriptArgs[0];
        connectionCallbackId = javascriptArgs[1];

        connectionManager = new ConnectionManager();
        connectionManager.Initialize(); // TODO can't we put this in the constructor?
        connectionManager.ByteReceived += connectionManager_ByteReceived;

        connectionManager.ConnectionSuccess += connectionManager_ConnectionSuccess;
        connectionManager.ConnectionFailure += connectionManager_ConnectionFailure;

        try
        {
            HostName deviceHostName = new HostName(macAddress);
            connectionManager.Connect(deviceHostName);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
            connectionManager_ConnectionFailure("Invalid Hostname");
        }

    }
开发者ID:RP-Z,项目名称:BluetoothSerial,代码行数:25,代码来源:BluetoothSerial.cs


示例20: Connect

        /// <summary>
        /// Attempt a TCP socket connection to the given host over the given port
        /// </summary>
        /// <param name="serverAddress">The address of the server</param>
        /// <param name="portNumber">The port number to connect</param>
        private bool Connect(string serverAddress, int portNumber) {
            HostName serverHost = new HostName(serverAddress);

            mSocket = new StreamSocket();
            mSocket.Control.KeepAlive = true;
            
            Task connectTask = mSocket.ConnectAsync(serverHost, portNumber.ToString()).AsTask();
            try {
                if(!connectTask.Wait(TIMEOUT)) {
                    // timed out connecting to the server
                    System.Diagnostics.Debug.WriteLine("Timed out connecting to TCP server");
                    return false;
                }
            } catch(AggregateException a) {
                // exception when running connect task. failed to connect to server
                System.Diagnostics.Debug.WriteLine("Failed to connect to TCP server. Error: " + a.GetBaseException().Message);
                return false;
            }

            // set up the writer 
            writer = new DataWriter(mSocket.OutputStream);

            // set up the reader
            reader = new DataReader(mSocket.InputStream);
            reader.InputStreamOptions = InputStreamOptions.Partial; // Set inputstream options so that we don't have to know the data size

            // start listening for messages
            Task.Run(() => StartReceiving()); // start receiving on a new thread
            Task.Run(() => StartKeepAlive()); // start receiving on a new thread
            return true;
        }
开发者ID:kktseng,项目名称:CritterCampClient,代码行数:36,代码来源:TCPWindowsPhone.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# BackgroundTransfer.BackgroundDownloader类代码示例发布时间:2022-05-26
下一篇:
C# Capture.MediaCaptureInitializationSettings类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap