15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Building P2P applications ❘ 1351<br />

}<br />

}<br />

break;<br />

The endpoint URL is validated, <strong>and</strong> then the WCF service is registered <strong>and</strong> started:<br />

// Check for null address<br />

if (serviceUrl == null)<br />

{<br />

// Display error <strong>and</strong> shutdown<br />

MessageBox.Show(this, "Unable to determine WCF endpoint.",<br />

"Networking Error", MessageBoxButton.OK, MessageBoxImage.Stop);<br />

Application.Current.Shutdown();<br />

}<br />

// Register <strong>and</strong> start WCF service.<br />

localService = new P2PService(this, username);<br />

host = new ServiceHost(localService, new Uri(serviceUrl));<br />

NetTcpBinding binding = new NetTcpBinding();<br />

binding.Security.Mode = SecurityMode.None;<br />

host.AddServiceEndpoint(typeof(IP2PService), binding, serviceUrl);<br />

try<br />

{<br />

host.Open();<br />

}<br />

catch (AddressAlreadyInUseException)<br />

{<br />

// Display error <strong>and</strong> shutdown<br />

MessageBox.Show(this, "Cannot start listening, port in use.",<br />

"WCF Error", MessageBoxButton.OK, MessageBoxImage.Stop);<br />

Application.Current.Shutdown();<br />

}<br />

A singleton instance of the service class is used to enable easy communication between the host app <strong>and</strong> the<br />

service (for sending <strong>and</strong> receiving messages). Also, note that security is disabled in the binding configuration<br />

for simplicity.<br />

Next, the System.Net.PeerToPeer namespace classes are used to register a peer name:<br />

}<br />

// Create peer name<br />

peerName = new PeerName("P2P Sample", PeerNameType.Unsecured);<br />

// Prepare peer name registration in link local clouds<br />

peerNameRegistration = new PeerNameRegistration(peerName, int.Parse(port));<br />

peerNameRegistration.Cloud = Cloud.AllLinkLocal;<br />

// Start registration<br />

peerNameRegistration.Start();<br />

When the Refresh button is clicked the RefreshButton_Click() event h<strong>and</strong>ler uses PeerNameResolver<br />

.ResolveAsync() to get peers asynchronously:<br />

private void RefreshButton_Click(object sender, RoutedEventArgs e)<br />

{<br />

// Create resolver <strong>and</strong> add event h<strong>and</strong>lers<br />

PeerNameResolver resolver = new PeerNameResolver();<br />

resolver.ResolveProgressChanged +=<br />

new EventH<strong>and</strong>ler(<br />

resolver_ResolveProgressChanged);<br />

resolver.ResolveCompleted +=<br />

new EventH<strong>and</strong>ler(<br />

resolver_ResolveCompleted);<br />

// Prepare for new peers<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!