本文整理汇总了C#中Windows.Networking.Sockets.DatagramSocket.BindEndpointAsync方法的典型用法代码示例。如果您正苦于以下问题:C# DatagramSocket.BindEndpointAsync方法的具体用法?C# DatagramSocket.BindEndpointAsync怎么用?C# DatagramSocket.BindEndpointAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Networking.Sockets.DatagramSocket
的用法示例。
在下文中一共展示了DatagramSocket.BindEndpointAsync方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PerformPeerDiscovery
public async void PerformPeerDiscovery()
{
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
if (socket == null)
{
socket = new DatagramSocket();
socket.MessageReceived += socket_MessageReceived;
try
{
await socket.BindEndpointAsync(null, "22002");
}
catch
{
// Swallow any already bound exceptions!
}
}
using (var outputStream = await socket.GetOutputStreamAsync(new HostName("230.0.0.1"), "22003"))
{
using (DataWriter wr = new DataWriter(outputStream))
{
wr.WriteString("**BECHARMING DISCOVERY**");
await wr.FlushAsync();
await wr.StoreAsync();
}
}
}
示例2: 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");
}
}
}
示例3: 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);
}
示例4: StartListening
public async void StartListening()
{
foreach (HostName localHostInfo in NetworkInformation.GetHostNames())
{
if (localHostInfo.IPInformation != null)
{
DatagramSocket socket = new DatagramSocket();
socket.MessageReceived += Sock_MessageReceived;
await socket.BindEndpointAsync(localHostInfo, "8888");
}
}
}
示例5: startListener
public async Task startListener()
{
try
{
listener = new DatagramSocket();
listener.MessageReceived += MessageReceived;
await listener.BindEndpointAsync(new HostName(IPAdress.LocalIPAddress()), portListener);
playPage.DisplayMessages(name + " :UDP Listener [local]:" + portListener + " started");
}
catch (Exception ex)
{
playPage.DisplayMessages(name + " :ERROR: UDP Listener [local]:" + portListener + " started\n" + ex.ToString());
}
}
示例6: DiscoverDevices
/// <summary>
/// @see http://www.johnthom.com/implementing-ssdp-search-in-windows-phone-8-using-winrt/
/// </summary>
public async Task DiscoverDevices()
{
int timeout = 3000;
var remoteIp = "239.255.255.250";
var remoteIpHostName = new Windows.Networking.HostName(remoteIp);
var port = "1900";
string query = "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: " + timeout.ToString() + "\r\n\r\n";
var buffer = Encoding.UTF8.GetBytes(query);
using (var socket = new DatagramSocket())
{
socket.MessageReceived += (sender, args) => {
Task.Run(() => {
using (var reader = args.GetDataReader())
{
byte[] respBuff = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(respBuff);
string response = Encoding.UTF8.GetString(respBuff, 0, respBuff.Length).ToLower();
response.Trim('\0');
ProcessSSDPResponse(response);
}
});
};
await socket.BindEndpointAsync(null, "");
socket.JoinMulticastGroup(remoteIpHostName);
using (var stream = await socket.GetOutputStreamAsync(remoteIpHostName, port))
{
await stream.WriteAsync(buffer.AsBuffer());
}
// Execute within timeout
await Task.Delay(timeout);
}
}
示例7: FindTvs
public async void FindTvs()
{
if (searchState == SearchState.Searching)
{
StopSearching();
}
tvSearchSocket = new DatagramSocket();
tvSearchSocket.MessageReceived += TvListenCompleted;
await tvSearchSocket.BindEndpointAsync(null, "");
tvSearchSocket.JoinMulticastGroup(multicastAddress);
StartedSearching();
SendSSDP();
tvSearchRetryTimer = new Timer(TvSearchRetry, null, TimeSpan.FromSeconds(tvSearchRetryTimeSeconds), TimeSpan.FromMilliseconds(-1));
tvSearchTimeoutTimer = new Timer(TvSearchTimeout, null, TimeSpan.FromSeconds(tvSearchTotalTimeSeconds), TimeSpan.FromMilliseconds(-1));
searchState = SearchState.Searching;
}
示例8: ServerConnection
public ServerConnection(Action<string> callbackFunction = null)
{
m_callbackFunction = callbackFunction;
// Connect to server using new thread task.
Task.Run(async () =>
{
m_udpSocket = new DatagramSocket();
m_udpSocket.MessageReceived += MessageReceivedCallback;
try
{
//await m_udpSocket.ConnectAsync(m_remoteHostName, m_remoteResponsePort);
await m_udpSocket.BindEndpointAsync(m_localHostName, m_localPort);
}
catch (Exception exception)
{
}
});
}
示例9: StartupAsync
public async Task<bool> StartupAsync(string multicastIP, int multicastPort)
{
await ShutdownAsync();
IsRunning = true;
this.MulticastIP = multicastIP;
this.MulticastPort = multicastPort;
try
{
socket = new DatagramSocket();
socket.MessageReceived += socket_MessageReceived;
await socket.BindEndpointAsync(null, multicastPort.ToString());
socket.JoinMulticastGroup(new HostName(multicastIP));
return true;
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("{0} occurred while starting multicast listener: {1}", ex.GetType().Name, ex.Message));
await ShutdownAsync();
return false;
}
}
示例10: StartListener_Click
/// <summary>
/// This is the click handler for the 'StartListener' button.
/// </summary>
/// <param name="sender">Object for which the event was generated.</param>
/// <param name="e">Event's parameters.</param>
private async void StartListener_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(ServiceNameForListener.Text))
{
rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage);
return;
}
if (CoreApplication.Properties.ContainsKey("listener"))
{
rootPage.NotifyUser(
"This step has already been executed. Please move to the next one.",
NotifyType.ErrorMessage);
return;
}
CoreApplication.Properties.Remove("serverAddress");
DatagramSocket listener = new DatagramSocket();
listener.MessageReceived += MessageReceived;
if (!String.IsNullOrWhiteSpace(InboundBufferSize.Text))
{
uint inboundBufferSize = 0;
if (!uint.TryParse(InboundBufferSize.Text, out inboundBufferSize))
{
rootPage.NotifyUser(
"Please provide a positive numeric Inbound buffer size.",
NotifyType.ErrorMessage);
return;
}
try
{
// Running both client and server on localhost will most likely not reach the buffer limit.
// Refer to the DatagramSocketControl class' MSDN documentation for the full list of control options.
listener.Control.InboundBufferSizeInBytes = inboundBufferSize;
}
catch (ArgumentException)
{
rootPage.NotifyUser("Please provide a valid Inbound buffer size.", NotifyType.ErrorMessage);
return;
}
}
LocalHostItem selectedLocalHost = null;
if ((BindToAddress.IsChecked == true) || (BindToAdapter.IsChecked == true))
{
selectedLocalHost = (LocalHostItem)AdapterList.SelectedItem;
if (selectedLocalHost == null)
{
rootPage.NotifyUser("Please select an address / adapter.", NotifyType.ErrorMessage);
return;
}
// The user selected an address. For demo purposes, we ensure that connect will be using the same
// address.
CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName);
}
// Save the socket, so subsequent steps can use it.
CoreApplication.Properties.Add("listener", listener);
// Start listen operation.
try
{
if (BindToAny.IsChecked == true)
{
// Don't limit traffic to an address or an adapter.
await listener.BindServiceNameAsync(ServiceNameForListener.Text);
rootPage.NotifyUser("Listening", NotifyType.StatusMessage);
}
else if (BindToAddress.IsChecked == true)
{
// Try to bind to a specific address.
await listener.BindEndpointAsync(selectedLocalHost.LocalHost, ServiceNameForListener.Text);
rootPage.NotifyUser(
"Listening on address " + selectedLocalHost.LocalHost.CanonicalName,
NotifyType.StatusMessage);
}
else if (BindToAdapter.IsChecked == true)
{
// Try to limit traffic to the selected adapter.
// This option will be overriden by interfaces with weak-host or forwarding modes enabled.
NetworkAdapter selectedAdapter = selectedLocalHost.LocalHost.IPInformation.NetworkAdapter;
await listener.BindServiceNameAsync(ServiceNameForListener.Text, selectedAdapter);
rootPage.NotifyUser(
"Listening on adapter " + selectedAdapter.NetworkAdapterId,
NotifyType.StatusMessage);
}
}
catch (Exception exception)
{
//.........这里部分代码省略.........
示例11: DiscoverBridge
public async Task DiscoverBridge(TimeSpan timeOut)
{
var multicastIP = new HostName("239.255.255.250");
var foundBridge = false;
using (var socket = new DatagramSocket())
{
socket.MessageReceived += async (sender, args) =>
{
var reader = args.GetDataReader();
var bytesRemaining = reader.UnconsumedBufferLength;
foreach (var line in reader.ReadString(bytesRemaining).Split(new String[1] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
{
if (line.StartsWith("LOCATION"))
{
var address = line.Split(new char[1] { ':' }, 2)[1];
var message = await _client.GetAsync(address);
if (message.IsSuccessStatusCode)
{
var messageContent = await message.Content.ReadAsStringAsync();
var buffer = Encoding.UTF8.GetBytes(messageContent);
}
}
}
foundBridge = true;
};
await socket.BindEndpointAsync(null, string.Empty);
socket.JoinMulticastGroup(multicastIP);
while(true)
{
foundBridge = false;
using (var stream = await socket.GetOutputStreamAsync(multicastIP, "1900"))
using (var writer = new DataWriter(stream))
{
var request = new StringBuilder();
request.AppendLine("M-SEARCH * HTTP/1.1");
request.AppendLine("HOST: 239.255.255.250:1900");
request.AppendLine("MAN: ssdp:discover");
request.AppendLine("MX: 3");
request.AppendLine("ST: ssdp:all");
writer.WriteString(request.ToString());
await writer.StoreAsync();
if (timeOut > TimeSpan.Zero)
{
await Task.Delay(timeOut);
}
if (foundBridge)
{
break;
}
}
}
}
}
示例12: AddDatagramSocketAsync
public async void AddDatagramSocketAsync(UInt16 port)
{
ThrowIfDisposed();
manager.NotifyUser("Adding stream socket listener for UDP port " + port, NotifyType.StatusMessage);
var endpointPairCollection = session.GetConnectionEndpointPairs();
DatagramSocket socket = new DatagramSocket();
SocketWrapper socketWrapper = new SocketWrapper(manager, null, socket);
socketList.Add(socketWrapper);
// Bind UDP socket for receiving messages (peer should call connect and send messages to this socket)
manager.NotifyUser("BindEndpointAsync...", NotifyType.StatusMessage);
await socket.BindEndpointAsync(endpointPairCollection[0].LocalHostName, Convert.ToString(port, CultureInfo.InvariantCulture));
manager.NotifyUser("BindEndpointAsync Done", NotifyType.StatusMessage);
manager.NotifyUser("AddDatagramSocketAsync...", NotifyType.StatusMessage);
await session.AddDatagramSocketAsync(socket);
manager.NotifyUser("AddDatagramSocketAsync Done", NotifyType.StatusMessage);
// Update manager so UI can add to list
manager.AddSocket(socketWrapper);
}