本文整理汇总了C#中Windows.Networking.Sockets.DatagramSocket.JoinMulticastGroup方法的典型用法代码示例。如果您正苦于以下问题:C# DatagramSocket.JoinMulticastGroup方法的具体用法?C# DatagramSocket.JoinMulticastGroup怎么用?C# DatagramSocket.JoinMulticastGroup使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Networking.Sockets.DatagramSocket
的用法示例。
在下文中一共展示了DatagramSocket.JoinMulticastGroup方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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);
}
示例2: 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());
}
}
示例3: Open
public async Task Open()
{
//CheckBackgroundTask();
//await CheckSocketAsync();
#region Simple socket creation
if (listenerSocket == null)
{
listenerSocket = new DatagramSocket();
listenerSocket.Control.DontFragment = true;
listenerSocket.Control.MulticastOnly = true;
listenerSocket.MessageReceived += DataReceived;
try
{
await listenerSocket.BindServiceNameAsync(localService);
listenerSocket.JoinMulticastGroup(new HostName(remoteMulticastAddress));
}
catch (Exception exception)
{
Close();
// If this is an unknown status it means that the error is fatal and retry will likely fail.
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
throw;
//rootPage.NotifyUser("Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage);
}
}
#endregion
}
示例4: 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;
}
示例5: 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");
}
}
}
示例6: 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);
}
示例7: ListenForTick
private async Task<DatagramSocket> ListenForTick(NetworkAdapter hostname)
{
var socket = new DatagramSocket();
socket.MessageReceived += OnMessageReceived;
await socket.BindServiceNameAsync(Settings.RemoteServiceName, hostname);
socket.JoinMulticastGroup(new HostName(Settings.MulticastAddress));
Log($"Listening on {hostname.NetworkAdapterId}:{Settings.RemoteServiceName}");
return socket;
}
示例8: 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);
}
}
示例9: StartListeningAsync
/// <summary>
/// Start listening.
/// </summary>
public override async Task<bool> StartListeningAsync()
{
bool status = false;
if (_listenerSocket == null)
{
_listenerSocket = new DatagramSocket();
_listenerSocket.MessageReceived += AdvertisementMessageReceivedFromManagerAsync;
await _listenerSocket.BindServiceNameAsync(ListenerPort);
_listenerSocket.JoinMulticastGroup(ListenerGroupHost);
status = true;
}
return status;
}
示例10: Start
public override async void Start()
{
if (Status == ListenerStatus.Listening)
return;
try
{
_datagramSocket = new DatagramSocket();
_datagramSocket.MessageReceived += DatagramSocketOnMessageReceived;
await _datagramSocket.BindServiceNameAsync(MulticastPort.ToString());
_datagramSocket.JoinMulticastGroup(MulticastIpAddress);
RaiseStatusChanged(ListenerStatus.Listening);
}
catch
{
RaiseStatusChanged(ListenerStatus.PortNotFree);
}
}
示例11: 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);
}
}
示例12: 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;
}
示例13: Resolve
public static IObservable<ZeroconfRecord> Resolve(string protocol)
{
return Observable.Create<ZeroconfRecord>(async observer =>
{
var socket = new DatagramSocket();
var s = Observable
.FromEventPattern
<TypedEventHandler<DatagramSocket, DatagramSocketMessageReceivedEventArgs>,
DatagramSocketMessageReceivedEventArgs>(
x => socket.MessageReceived += x, _ => socket.Dispose())
.Select(ProcessMessage)
.Where(x => x != null)
.Subscribe(observer);
await socket.BindServiceNameAsync("5353");
socket.JoinMulticastGroup(new HostName("224.0.0.251"));
var os = await socket.GetOutputStreamAsync(new HostName("224.0.0.251"), "5353");
var writer = new DataWriter(os);
WriteQueryMessage(protocol, writer);
writer.StoreAsync();
return s;
});
}
示例14: 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;
}
}
示例15: CheckSocketAsync
private async Task CheckSocketAsync()
{
try
{
SocketActivityInformation socketInformation;
if (!SocketActivityInformation.AllSockets.TryGetValue(socketId, out socketInformation))
{
var socket = new DatagramSocket();
socket.Control.DontFragment = true;
socket.Control.MulticastOnly = true;
socket.EnableTransferOwnership(task.TaskId, SocketActivityConnectedStandbyAction.Wake);
await socket.BindServiceNameAsync(localService);
socket.JoinMulticastGroup(new HostName(remoteMulticastAddress));
// To demonstrate usage of CancelIOAsync async, have a pending read on the socket and call
// cancel before transfering the socket.
//DataReader reader = new DataReader(socket.InputStream);
//reader.InputStreamOptions = InputStreamOptions.Partial;
//var read = reader.LoadAsync(250);
//read.Completed += (info, status) =>
//{
//};
//await socket.CancelIOAsync();
socket.TransferOwnership(socketId);
socket = null;
}
//rootPage.NotifyUser("Connected. You may close the application", NotifyType.StatusMessage);
}
catch (Exception exception)
{
//rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage);
}
}