本文整理汇总了C#中Windows.Networking.Sockets.DatagramSocket.GetOutputStreamAsync方法的典型用法代码示例。如果您正苦于以下问题:C# DatagramSocket.GetOutputStreamAsync方法的具体用法?C# DatagramSocket.GetOutputStreamAsync怎么用?C# DatagramSocket.GetOutputStreamAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Networking.Sockets.DatagramSocket
的用法示例。
在下文中一共展示了DatagramSocket.GetOutputStreamAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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());
}
}
示例2: 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);
}
示例3: ExecuteDiscoveryTask
private async Task ExecuteDiscoveryTask()
{
int repeatTime = EndpointController.REPEAT_DISCOVERY_TASK / 2;
while (running)
{
Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Started Cloudlet Discovery using Multicast UDP");
retry = 0;
DatagramSocket socketSent = null;
DatagramSocket socketReplay = null;
try
{
socketSent = new DatagramSocket();
await socketSent.BindEndpointAsync(null, string.Empty);
socketSent.JoinMulticastGroup(ip);
socketReplay = new DatagramSocket();
socketReplay.MessageReceived += SocketOnMessageReceived;
await socketReplay.BindServiceNameAsync(replyCloudletPort.ToString());
using (DataWriter writer = new DataWriter(await socketSent.GetOutputStreamAsync(ip, multicastPort.ToString())))
{
while (retry < 60 && running)
{
writer.WriteString("mpos_cloudlet_req");
await writer.StoreAsync();
await writer.FlushAsync();
await Task.Delay(500);
retry++;
}
}
}
catch (IOException e)
{
Debug.WriteLine("## [DiscoveryCloudletMulticast]: Any problem with i/o in multicast system!\n" + e.ToString());
}
finally
{
socketSent.Dispose();
socketReplay.Dispose();
socketSent = null;
socketReplay = null;
}
if (running)
{
Debug.WriteLine(">> [DiscoveryCloudletMulticast]: Retry Discovery Cloudlet, in " + repeatTime + " ms");
await Task.Delay(repeatTime);
}
else
{
Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Finished Discovery Cloudlet");
}
}
}
示例4: SendMagicPacket
/// <summary>
/// Attempts to send a magic packet to the desination hostname, on the specified port with the specified MAC address.
/// </summary>
/// <param name="destination">Destination hostname or IP address.</param>
/// <param name="destinationPort">Destination port number.</param>
/// <param name="targetMac">Destination MAC address. Bytes can be separated by colons, dashes, or nothing.</param>
/// <returns>True if magic packet is sent successfully, false otherwise.</returns>
public async Task<bool> SendMagicPacket(Windows.Networking.HostName destination, uint destinationPort, string targetMac)
{
try
{
DatagramSocket _socket = new DatagramSocket();
using (var stream = await _socket.GetOutputStreamAsync(destination, destinationPort.ToString()))
{
//Split on common MAC separators
char? splitChar = null;
if (targetMac.Contains('-'))
splitChar = '-';
else if (targetMac.Contains(':'))
splitChar = ':';
else if (targetMac.Contains(' '))
splitChar = ' ';
//Turn MAC into array of bytes
byte[] macAsArray;
if (splitChar != null)
{
macAsArray = targetMac.Split((char)splitChar)
.Select(b => Convert.ToByte(b, 16))
.ToArray<byte>();
}
else
{
//Jump through MAC-string, reading 2 chars at a time
macAsArray = Enumerable.Range(0, targetMac.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(targetMac.Substring(x, 2), 16)) //16 = hexadecimal
.ToArray();
}
List<byte> magicPacket = new List<byte> { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
//A WoLAN magic packet is just FF FF FF FF FF FF, then the target MAC adress repeated 16 times.
for (int i = 0; i < 16; i++)
{
magicPacket = magicPacket.Concat(macAsArray).ToList();
}
using (DataWriter writer = new DataWriter(stream))
{
writer.WriteBytes(magicPacket.ToArray<byte>());
await writer.StoreAsync();
await writer.FlushAsync();
return true;
}
}
}
catch (Exception e)
{
Debug.WriteLine(e);
return false;
}
}
示例5: LocateBridgesAsync
/// <summary>
/// Returns list of bridge IPs
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<string>> LocateBridgesAsync(TimeSpan timeout)
{
if (timeout <= TimeSpan.Zero)
throw new ArgumentException("Timeout value must be greater than zero.", "timeout");
var discoveredDevices = new List<string>();
var multicastIP = new HostName("239.255.255.250");
using (var socket = new DatagramSocket())
{
//Handle MessageReceived
socket.MessageReceived += (sender, e) =>
{
var reader = e.GetDataReader();
var bytesRemaining = reader.UnconsumedBufferLength;
var receivedString = reader.ReadString(bytesRemaining);
var location = receivedString.Substring(receivedString.ToLower().IndexOf("location:", System.StringComparison.Ordinal) + 9);
receivedString = location.Substring(0, location.IndexOf("\r", System.StringComparison.Ordinal)).Trim();
discoveredDevices.Add(receivedString);
};
await socket.BindEndpointAsync(null, string.Empty);
socket.JoinMulticastGroup(multicastIP);
var start = DateTime.Now;
do
{
using (var stream = await socket.GetOutputStreamAsync(multicastIP, "1900"))
using (var writer = new DataWriter(stream))
{
string request = "M-SEARCH * HTTP/1.1\r\n" +
"HOST:239.255.255.250:1900\r\n" +
//"ST:urn:schemas-upnp-org:device:Basic:1\r\n" + //Alternative
// "ST:upnp:rootdevice\r\n" + //Alternative
"ST:SsdpSearch:all\r\n" +
"MAN:\"ssdp:discover\"\r\n" +
"MX:3\r\n\r\n\r\n";
writer.WriteString(request.ToString());
await writer.StoreAsync();
}
}
while (DateTime.Now.Subtract(start) < timeout); // try for thee seconds
}
return await FilterBridges(discoveredDevices);
}
示例6: OnMessageReceived
private async void OnMessageReceived(
DatagramSocket sender,
DatagramSocketMessageReceivedEventArgs args)
{
var senderHostname = new HostName(args.RemoteAddress.RawName);
var writer = new DataWriter(await sender.GetOutputStreamAsync(senderHostname, args.RemotePort));
var stream = new NetworkStream(args.GetDataReader(), writer);
this.clients.ForEach(x => x.MessageReceived(this, stream));
}
示例7: StartServer
public async void StartServer(string port)
{
_socket = new DatagramSocket();
var control = _socket.Control;
_socket.MessageReceived += OnMessageRecived;
await _socket.BindServiceNameAsync(port);
var host = new HostName("192.168.137.1");
var outputStream = await _socket.GetOutputStreamAsync(host, "8001");
_writer = new DataWriter(outputStream);
}
示例8: DoWakeOnLan
private async Task DoWakeOnLan(string macAddress, string ipAddress, string port)
{
var socket = new DatagramSocket();
await socket.BindServiceNameAsync("0");
var o = await socket.GetOutputStreamAsync(new HostName(ipAddress), port);
var writer = new DataWriter(o);
writer.WriteBytes(GetBuffer(macAddress));
await writer.StoreAsync();
socket.Dispose();
}
示例9: Search
private async void Search(string st, TimeSpan? timeout = null)
{
Log("Search - " + st);
var ssdp_data = new StringBuilder()
.Append("M-SEARCH * HTTP/1.1").Append("\r\n")
.Append("HOST: ").Append(MULTICAST_ADDRESS).Append(":").Append(SSDP_PORT.ToString()).Append("\r\n")
.Append("MAN: ").Append("\"ssdp:discover\"").Append("\r\n")
.Append("MX: ").Append(MX.ToString()).Append("\r\n")
.Append("ST: ").Append(st).Append("\r\n")
.Append("\r\n")
.ToString();
var adapters = TargetNetworkAdapters ?? await GetActiveAdaptersAsync().ConfigureAwait(false);
await Task.WhenAll(adapters.Select(async adapter =>
{
using (var socket = new DatagramSocket())
{
socket.Control.DontFragment = true;
socket.MessageReceived += OnDatagramSocketMessageReceived;
try
{
await socket.BindServiceNameAsync("", adapter);
using (var output = await socket.GetOutputStreamAsync(MULTICAST_HOST, SSDP_PORT.ToString()))
{
using (var writer = new DataWriter(output))
{
writer.WriteString(ssdp_data);
await writer.StoreAsync();
}
}
await Task.Delay(timeout ?? DEFAULT_TIMEOUT).ConfigureAwait(false);
Log("Search Timeout");
await socket.CancelIOAsync();
}
catch (Exception e)
{
Log("Failed to send multicast: " + e.StackTrace);
}
socket.MessageReceived -= OnDatagramSocketMessageReceived;
}
})).ConfigureAwait(false);
Finished?.Invoke(this, new EventArgs());
}
示例10: SendTick
private async Task SendTick()
{
using (var socket = new DatagramSocket())
{
await socket.BindServiceNameAsync(string.Empty);
socket.JoinMulticastGroup(new HostName(BroadcastAddress));
var outputStream =
await socket.GetOutputStreamAsync(new HostName(BroadcastAddress), RemoteServiceName);
var buffer = Encoding.UTF8.GetBytes("TT_SEND_DEVICE_INFO");
await outputStream.WriteAsync(buffer.AsBuffer());
await outputStream.FlushAsync();
Debug.WriteLine("TICK Broadcasted to {0}:{1}", BroadcastAddress, RemoteServiceName);
}
}
示例11: _socket_OnMessageReceived
private async void _socket_OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs e)
{
var reader = e.GetDataReader();
string message = reader.ReadString(reader.UnconsumedBufferLength);
Logger.Trace("Message from {0}:{1}:\n{2}", e.RemoteAddress.RawName, e.RemotePort, message);
IOutputStream outputStream = await sender.GetOutputStreamAsync(e.RemoteAddress, e.RemotePort);
Received(this, new PeerCommandEventArgs
{
Data = message,
Peer = new RemotePeer(_serializer, this, outputStream, e.RemoteAddress, e.RemotePort),
});
}
示例12: FindServers
public async Task<List<ServerDiscoveryInfo>> FindServers(int timeoutMs, CancellationToken cancellationToken)
{
var result = new List<ServerDiscoveryInfo>();
var tcs = new TaskCompletionSource<List<ServerDiscoveryInfo>>();
var ct = new CancellationTokenSource(timeoutMs);
ct.Token.Register(() => tcs.SetResult(result), useSynchronizationContext: false);
var socket = new DatagramSocket();
socket.MessageReceived += (sender, args) =>
{
try
{
var reader = args.GetDataReader();
uint stringLength = args.GetDataReader().UnconsumedBufferLength;
var rawData = args.GetDataReader().ReadString(stringLength);
var server = JsonConvert.DeserializeObject<ServerDiscoveryInfo>(rawData);
result.Add(server);
}
catch
{
tcs.SetResult(result);
}
};
try
{
using (var stream = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), "7359"))
{
using (var writer = new DataWriter(stream))
{
var data = Encoding.UTF8.GetBytes("who is MediaBrowserServer_v2?");
writer.WriteBytes(data);
writer.StoreAsync();
}
}
}
catch
{
tcs.SetResult(result);
}
return await tcs.Task;
}
示例13: DiscoverDevices
public async Task DiscoverDevices()
{
string response = String.Empty;
DatagramSocket socket = new DatagramSocket();
socket.MessageReceived += Socket_MessageReceived;
using (var stream = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), OSCClient.PORT))
using (var writer = new DataWriter(stream))
{
OSCMessage msg = new OSCMessage("/info");
writer.WriteBytes(msg.BinaryData);
await writer.StoreAsync();
}
}
示例14: Send
public async Task Send(byte[] command)
{
using (var socket = new DatagramSocket())
{
using (var stream = await socket.GetOutputStreamAsync(this.hostName, this.port))
{
using (var dataWriter = new DataWriter(stream))
{
dataWriter.WriteBytes(command);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
}
}
}
示例15: Search
public async void Search()
{
if (isSearching)
return;
isSearching = true;
var socket = new DatagramSocket();
socket.MessageReceived += async (sender, args) =>
{
DataReader reader = args.GetDataReader();
uint count = reader.UnconsumedBufferLength;
string data = reader.ReadString(count);
var response = new Dictionary<string, string>();
foreach (
string x in
data.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None))
{
if (x.Contains(":"))
{
string[] strings = x.Split(':');
response.Add(strings[0].ToLower(), x.Remove(0, strings[0].Length + 1));
}
}
Device device = await GetXml(response);
Debug.WriteLine($"Device found : {device.DeviceType.friendlyName}");
if (DeviceFound != null)
DeviceFound(this, new DeviceFoundEventArgs(device));
};
IOutputStream stream = await socket.GetOutputStreamAsync(new HostName("239.255.255.250"), "1900");
const string message = "M-SEARCH * HTTP/1.1\r\n" +
"HOST: 239.255.255.250:1900\r\n" +
"ST:upnp:rootdevice\r\n" +
"MAN:\"ssdp:discover\"\r\n" +
"MX:3\r\n\r\n";
var writer = new DataWriter(stream) { UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8 };
writer.WriteString(message);
await writer.StoreAsync();
isSearching = false;
}