本文整理汇总了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;
}
示例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;
}
}
示例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);
}
示例4: Settings
public Settings()
{
socket = new StreamSocket();
ConnectToServer();
host = new HostName("192.168.12.171");
this.InitializeComponent();
}
示例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);
}
示例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;
}
}
示例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 });
}
}
示例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);
}
示例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);
}
示例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;
}
示例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;
}
}
示例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);
}
示例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;
}
}
示例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);
}
}
示例15: FrameUploader
public FrameUploader(string id, IPAddress address, int port)
{
_host = new HostName(address.ToString());
_port = port.ToString();
_cameraId = id;
UploadComplete = () => { };
}