15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

1350 ❘ ChaPTer 45 peer-tO-peer netwOrkinG<br />

After you have built the application you can test it either by copying it to other computers in your local<br />

network <strong>and</strong> running all instances, or by running multiple instances on one computer. If you choose the latter<br />

option you must remember to change the port used for each instance by changing individual config files (copy<br />

the contents of the Debug directory on your local computer <strong>and</strong> edit each config file in turn). The results will<br />

be clearer in both ways of testing this application if you also change the username for each instance.<br />

When the peer applications are running, you can use the Refresh button to obtain a list of peers asynchronously.<br />

When you have located a peer you can send a default message by clicking the Message button for the peer.<br />

Figure 45-7 shows this application in action with three instances running on one machine. In the figure, one<br />

peer has just messaged another <strong>and</strong> this has resulted in a dialog box.<br />

figure 45-7<br />

Most of the work in this application takes place in the Window_Loaded() event h<strong>and</strong>ler for the Window1<br />

window. This method starts by loading configuration information <strong>and</strong> setting the window title with the<br />

username:<br />

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

{<br />

// Get configuration from app.config<br />

string port = ConfigurationManager.AppSettings["port"];<br />

string username = ConfigurationManager.AppSettings["username"];<br />

string machineName = Environment.MachineName;<br />

string serviceUrl = null;<br />

// Set window title<br />

this.Title = string.Format("P2P example — {0}", username);<br />

code snippet Window1.xaml.cs<br />

Next the peer host address is used along with the configured port to determine the endpoint on which to<br />

host the WCF service. The service will use NetTcpBinding binding, so the URL of the endpoint uses the<br />

net.tcp protocol:<br />

// Get service url using IPv4 address <strong>and</strong> port from config file<br />

foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))<br />

{<br />

if (address.AddressFamily ==<br />

System.Net.Sockets.AddressFamily.InterNetwork)<br />

{<br />

serviceUrl = string.Format("net.tcp://{0}:{1}/P2PService",<br />

address, port);<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!