Building a REALLY simple WCF P2P application

Often times when I’m looking at playing with a new technology that it becomes extremely difficult to find a simple stripped down easy-to-use chunk of code that also walks through, in-depth, the concepts and reasoning behind the code. This particular code chunk began as I started exploring the Microsoft WCF’s P2P networking services and found a rather distinct lack of code that explained the hows and whys of building a Peer to Peer network.

P2P Basics

Ok. Low level building blocks.

First, everybody (who’s interested in P2P) should already understand the client server paradigm, if not, there are many wonderfully detailed articles to explain the details. In short we have N clients all connected to 1 server. Client A sends a message to the server, the server decides what to do, and then may or may not send a response to Client A and / or Client B, Client C… etc… In a peer to peer network on the other hand, everyone is the client, everyone is a server. Because of this, the client / server naming scheme goes away by popular vote and everyone is called a node or a peer. When a node is connected to other nodes that whole group is called a mesh (or graph, or cloud).

Now, in a pure P2P network there is no central authority to help or govern how nodes find each other to form a mesh or how meshes are initially created.  Every node is connected to some number of other nodes, which are then connected to more nodes and so on. When one node wishes to communicate with another node (or nodes) the message is first passed on to the nodes that the first node knows about. These nodes in turn pass along the message on to other nodes that they know about and so on until finally everybody has seen the message.

One of the best, and probably most used, examples of a peer to peer network is the chat room. Until someone creates it, the chat room does not exist, but once it’s created people can be invited, join, and send messages that appear on everybody else’s screen. Even if the original person leaves the chat room, the room still exists as long as there are participants logged in. Once the last person leaves the chat room no longer exists.

Ping – The P2P Application

Note: I really dislike configuration files in demos or tutorials unless it’s a large application or showing how a particular aspect of a configuration file works. The fact that I can tell a static factory to build me something with a string name that corresponds to another file that somehow gets found, loaded, and happens to reference compiled type that then has a hidden class generated that implements that interface and is passed, bugs me when I’m trying to learn something.

If your going to follow along with this, your going to need .NET 3.5 installed and be running XP SP3, Vista, Win7 or Server 08. Visual Studio doesn’t hurt either.

To set up your project crack open Visual Studio and spin up a new Console Application, call it SimpleP2PExample. Once you have that open go over to the project, right click and Add Service Reference to System.ServiceModel, this allows you to use .NET’s WCF stuff in your app. You can choose to split up each class or interface into its own file or not: Up to you.

  1. //Contract for our network. It says we can 'ping'
  2. [ServiceContract(CallbackContract = typeof(IPing))]
  3. public interface IPing
  4. {
  5. [OperationContract(IsOneWay = true)]
  6. void Ping(string sender, string message);
  7. }

Alright, first of all, attributes. If you don’t know what they are, then here’s the low down mouthful one line explanation:

Attributes are essentially binary metadata associated with a class, method, property or whatever that provides additional information about whatever it’s “Decorating”.

The first attribute is the service contract. Wait a second. Contracts.

In our node-talking-to-other-nodes scenario, somehow they have to know how to talk to each other, if I asked what the size of the door was and you handed me a window, I have NO idea what that means or what that represents. A contract defines exactly what I’m telling you, what I’m expecting back, how, and when.

In this case we’re defining a contract that has one operation, a method called Ping. We know that when node A talks to node B that if node A says “Hey, Ping(“MyName”, “Hello.”) to Node B that node B will know what to do with that and how to pass it along to other nodes. It’s also specifies that I don’t expect Node B to give me anything back.

Now, the implementation.

  1. //implementation of our ping class
  2. public class PingImplementation : IPing
  3. {
  4. public void Ping(string sender, string message)
  5. {
  6. Console.WriteLine("{0} says: {1}", sender, message);
  7. }
  8. }

Fairly simple, whenever we receive a ping from another node, this method will be executed.

The Peer Class

Alright, now the fun, magic, and games begin. We’re going to create a class called peer, which will contain all our service start / stop code and also hold our implementation of PingImplementation.

  1. public class Peer
  2. {
  3. public string Id { get; private set; }
  5. public IPing Channel;
  6. public IPing Host;
  8. public Peer(string id)
  9. {
  10. Id = id;
  11. }
  12. }

In order to identify an individual node in the network, so that we know who’s who and don’t get everything mixed up, it’s customary to have a unique Id that’s assigned to the peer. Now, we have two IPing variables, the best way to describe them would be incoming and outgoing. An instance of the PingImplementation class will go in Host since it will be receiving any incoming communication from other nodes; The Channel is used to communicate out to other nodes and is built up via a factory.

  1. public void StartService()
  2. {
  3. var binding = new NetPeerTcpBinding();
  4. binding.Security.Mode = SecurityMode.None;
  6. var endpoint = new ServiceEndpoint(
  7. ContractDescription.GetContract(typeof(IPing)),
  8. binding,
  9. new EndpointAddress("net.p2p://SimpleP2P"));
  11. Host = new PingImplementation();
  13. _factory = new DuplexChannelFactory(
  14. new InstanceContext(Host),
  15. endpoint);
  17. var channel = _factory.CreateChannel();
  19. ((ICommunicationObject)channel).Open();
  21. // wait until after the channel is open to allow access.
  22. Channel = channel;
  23. }
  24. private DuplexChannelFactory<IPing>; _factory;

This is what we will use to start the peer.  This is the part where I’ve built up what could have been done in the configuration file with code instead.

Lets take it from the top.  First off, we have our binding; this defines what communication protocol we are going to be using, and as this is a PeerToPeer app… we use NetPeerTcpBinding().  You’ll also notice that in the next line I set the security mode to none; this is done for simplicities sake. There’s three types of security modes, including None, Message, Transport and TransportWithMessageCredential. Its a bit beyond the scope of this post, but Message security ensures that the message was not tampered with as it was passed from peer to peer, Transport security ensures that the connection between nodes is secure, and TransportWithMessageCredential does both.

Now, our application needs an endpoint, essentially, an service endpoint is a set of information that is exposed outside of the application (in this case on the network as well) so that others can access it. The endpoint defines the address it can be reached at, the contract, and the method that should be used to communicate. In this case, we build up our endpoint by using ContractDescription.GetContract to generate a contract class off of our IPing interface, our network type binding, and an endpoint address where this endpoint can be reached.

Finally, we create a new instance of our PingImplementation class as the Host, and we create our channel factory. A DuplexChannelFactory allows for two way communication, the first parameter is the object that you want to receive incoming calls, and the endpoint is where those calls are coming from. The factory then creates the channel and a whole bunch of magical things happen.

If you’ll remember, our channel is of type IPing, the Duplex Factory performs some magic and generates a concrete implementation of your interface (it also implements ICommunicationObject, which is why you’ll sometimes see people create another interface called something like “IPingChannel : IPing, ICommunicationObject”, it does make it so that you don’t have to cast it, but for the purpose of this post it’s not necessary). Imagine that it takes your interface, implements all the methods and properties with all the cool DuplexChannel code needed to talk back and fourth, creates an instance, and returns it to you.

Finally, I call open on my channel to let the world see that my brand new channel and endpoint are ready for business.

  1. public void StopService()
  2. {
  3. ((ICommunicationObject)Channel).Close();
  4. if (_factory != null)
  5. _factory.Close();
  6. }

Now, it’s all well and good, until your done. Then you need to close you channel and factory, this should be pretty self explanatory at this point.  Remember our channel is an ICommunicationObject in addition to being a IPing object, so we cast and close, then check to see if our factory is null, and if not, close that as well.

Threading The Peer Class

Something I chose to do was make the peer threaded. This allows me to drop it into an application, in a thread, and receive and push stuff into it at my leisure. To do this I add in a:

  1. private readonly AutoResetEvent _stopFlag = new AutoResetEvent(false);

This will allow me to block a method of the thread until I decide fire it (When I stop the peer).

  1. public void Run()
  2. {
  3. Console.WriteLine("[ Starting Service ]");
  4. StartService();
  6. Console.WriteLine("[ Service Started ]");
  7. _stopFlag.WaitOne();
  9. Console.WriteLine("[ Stopping Service ]");
  10. StopService();
  12. Console.WriteLine("[ Service Stopped ]");
  13. }
  15. public void Stop()
  16. {
  17. _stopFlag.Set();
  18. }

The run method embodies the lifecycle of this peer. When the peer thread starts into the run method it will start the service, wait until the stop flag is fired (when the Stop() method is called), and then stop and dispose the service.

Putting It All Together
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Count() <= 1)
  6. {
  7. for (int i = 0; i < 4; i++)
  8. {
  9. Process.Start("SimpleP2PExample.exe");
  10. }
  11. }
  13. new Program().Run();
  14. }
  16. public void Run()
  17. {
  18. Console.WriteLine("Starting the simple P2P demo.");
  20. var peer = new Peer("Peer(" + Guid.NewGuid() + ")");
  21. var peerThread = new Thread(peer.Run) {IsBackground = true};
  22. peerThread.Start();
  24. //wait for the server to start up.
  25. Thread.Sleep(1000);
  27. while (true)
  28. {
  29. Console.Write("Enter Something: ");
  30. string tmp = Console.ReadLine();
  32. if (tmp == "") break;
  34. peer.Channel.Ping(peer.Id, tmp);
  35. }
  37. peer.Stop();
  38. peerThread.Join();
  39. }
  40. }

From top to bottom, the Main method of the application checks to see if it’s the first one of this application to have started up, if it its, then it starts four additional processes (Note that if you called your project something other than SimpleP2PExample, you will need to replace the the string in Process.Start to be the name as the executable file your project generates).

The run method is also fairly simple, it creates a new instance of the Peer class, assigns it a GUID, creates a thread for the peer’s run method, starts up the thread and pauses to wait for the peer’s thread to start.  We then enter a loop until the user presses enter without inputting any text. Any text that is put in is transmitted over the peer channel using the peer’s id and the message. Once we’ve finished, we stop the session and wait for the peerThread to exit and join back up with the main thread. We then exit.

Wrap Up

I hope this helps someone out there get a better understanding of the basic concepts of a simple Peer to Peer application. Feel free to leave feedback!

Paul Rohde

57 thoughts on “Building a REALLY simple WCF P2P application

  1. Paul, I appreciate the post. While a lot of this is over my head, this will be very helpful fighting the learning curve with the wizards and config files knowing what’s happening underneath.

    BTW, my visual studio is complaining that “Using the generic type ‘System.ServiceModel.DuplexChannelFactory’ requires ‘1’ type arguments”

    Any help here?

  2. Paul, I realized that the code example lost the type enclosure because of the < and >

    So I’m assuming that the type that should be passed here is IPing.

  3. That’s correct, the type should be IPing for the DuplexChannelFactory, putting that in should solve the type arguments error your getting. Somehow wordpress and pre formatted text don’t seem to be getting along very well this afternoon.

    Glad you found it useful, hopefully its a good enough starting point to get you well on your way!

  4. Hi there! Some time ago I started looking for some good tutorials on WCF an P2P and finally gave up because they have been all badly written and concepted – but yours is nice, easy, thx!

  5. Hi.
    Nice tutorial, could have used a few hints on the usings, but I figured it out, as well as the other stuff, so now it builds. However when I debug, it fires 5 consoles, and after a short while the program crashes. It then asks me to send 4 error reports (4 of the consoles are closed), and tells me that on the line

    var channel = _factory.CreateChannel();

    , it says:
    InvalidOperationException was unhandled
    Resolver must be specified. The default resolver (PNRP) is not available. Please refer to the documentation with your system for details on how to install and enable PNRP.

    Do you have any idea of what could be the issue?

  6. Thanks Paul.

    Well written, really simple and explanatory…
    I was able to write my own working P2P application code while reading this and instantly rename members, interfaces etc. to match better to my way of thinking and the context (so IPing was renamed to IExternalRequest, channel to requestSender, host to requestReceiver).

    I started to read about 5 similar attempts to explain this 2 hours ago but always stopped confident there MUST BE an article on WEB explaining it briefly, clearly, simply, properly… :-)


  7. This version of your article came out better than the one on Interknowlegy. The Internknowlegy version lacked some of the labels on the listings making it a bit hard to see where they went. One minor point, though. In both versions you tell the reader to “Add Service Reference” to System.ServiceModel. You should have just said “Add Reference”. The tyros will be trying to find a service reference somewhere on the web.

  8. Very nice and easy article, it runs and works fine.
    I commented the for statement to run just once and executed another instance on another computer on the network and amazingly it transfered messages WOW
    But it didnt work on the internet, Im wondering how to make it work over the internet?

    • I’m glad you liked my article and that it was able to get you up and running! The problem with extending this over the internet is getting the clients to find each other in the first place. Your best bet is probably to look for a C# chat client demo (Since that will *probably* show you how to setup a server, a wcf connection to the server and how to connect multiple clients).

  9. Paul, thanks for your good written tutorial. As i can see at comments & my badly experience, we can’t use net.p2p via internet … so we need a server? We can’t implement client-client ( peer to peer ) direct connection working on Internet ? ;/

    • Hi Makis,

      You can, but you need a service that tells everyone how to connect with one another. Think about it like this, if I said “Take this piece of mail to bobs house” your first question would be “well, where is bobs house? Who is bob?” Without some way of saying “This is who bob is, and this is where he lives” there’s no good way to find bob. I suppose you could go knocking on every door but it’s not efficient.

      So to answer your question, there has to be some central place that the peers connect to too just figure out where the other peers are. Once they know the address of the peers they don’t need the server, but that initial connection requires it.

      • Hi Paul, suppose you knew already knew the IP address & port of the other guy, what would you change in your code above to allow communication over a network? I have tried just using new EndpointAddress(“net.p2p://” + partnerAddress) where partnerAddress is user input – it’s set to localhost:9005 on one computer and on the second. (That’s the IP of the first computer) but this doesn’t work. The application runs on each device but each doesn’t display the messages sent by the other.

  10. This is a great one I must say,
    I am a newbie to WCF
    One question what is the _factory ???

    doesnt exist in current context???

  11. Hi there, I got it to work via

    DuplexChannelFactory _Factory = new DuplexChannelFactory(new InstanceContext(IncomingHost), endpoint);

    but I get an error with :
    private DuplexChannelFactory; _Factory;

    _Factory could not be found????

  12. Hi Paul,
    Thank you for taking the time to create this tutorial. Two quick questions if I may: How do I configure it to work across the domain (it only works on my pc)? How do you specify the mesh in order to limit which computers the message goes to?

  13. sir Paul im a student and im working for my thesis sir can you give me some idea about the codes for peer 2 peer games im creating a game called Game of the Generals , my message field are okey its connect to other pc but the main problem is how can the other player saw the movements of the other player

  14. I’ve been browsing on-line more than 3 hours as of late, yet I never discovered any interesting article like yours.
    It is beautiful value sufficient for me. In my view, if all webmasters and bloggers made excellent content as you did,
    the web will be a lot more useful than ever before.

  15. hi!,I love your writing very a lot! percentage we keep up a correspondence more approximately your post on AOL?
    I need an expert on this space to resolve my problem.
    Maybe that’s you! Looking ahead to see you.

  16. I have to thank you for the efforts you’ve put in penning
    this site. I’m hoping to see the same high-grade content from you in the future as well.
    In truth, your creative writing abilities has motivated me to get my
    own, personal website now ;)

  17. hello!,I like ylur wrting vesry so much! proportion wee keep up a correspondence extra approximately your post on AOL?
    I need a specialist on this area to resolve my problem.
    Maybe that’s you! Taking a look forward to look you.

  18. It’s difficult to find educated people in this particular subject, however, you seem like you know what you’re talking about!

  19. Hi there I am so grateful I found your website,
    I really found you by error, while I was looking on Askjeeve for something
    else, Nonetheless I am here now and would just like to say cheers for a
    marvelous post and a all round entertaining blog (I also
    love the theme/design), I don’t have time to read
    it all at the minute but I have saved it and also included your RSS feeds, so when I have time I will be back to read
    a great deal more, Please do keep up the excellent b.

  20. Unquestionably believe that which you stated. Your favorite reason seemed to be on the net the easiest thing to be aware of.
    I say to you, I certainly get irked while people think about worries that they just don’t know about.
    You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal.
    Will likely be back to get more. Thanks

  21. What i do not understood is actually how you’re not
    actually a lot more neatly-appreciated than you may
    be now. You are very intelligent. You realize therefore significantly when it comes to this
    matter, produced me in my view imagine it from a lot of varied angles.
    Its like women and men are not interested unless it’s
    one thing to accomplish with Lady gaga! Your personal stuffs excellent.
    At all times maintain it up!

  22. Thanks for any other informative website. The place else may just I am getting that kind
    of info written in such a perfect means? I’ve a challenge that I’m simply
    now operating on, and I have been at the glance out for
    such info.

  23. Wonderful beat ! I would like to apprentice whilst you
    amend your site, how could i subscribe for a weblog web site?

    The account helped me a appropriate deal. I were a little
    bit acquainted of this your broadcast provided brilliant clear concept

  24. Whats up very nice blog!! Man .. Beautiful .. Superb ..
    I will bookmark your website and take the feeds also?
    I am glad to search out numerous helpful information here in the submit, we’d like develop more techniques on this regard,
    thanks for sharing. . . . . .

Leave a Reply

Your email address will not be published. Required fields are marked *