In this post, I’ll demonstrate a chat application and provide complete source code and instructions for creating it. It can then serve as a great starting point for being modified to create any sort of peer-to-peer application with a flexible GUI interface.
Each one of those buzzwords in the title is important for this post, and I’ve tried to include enough information for this to be a helpful introduction to any one of them:
Our application will consist of a single Visual Studio solution that contains two projects [see “Introduction to Solutions, Projects, and Items”]. The first project we’ll create will define the GUI front-end and the second will define all the application logic and networking functionality.
To begin, open Visual Studio 2010 and go to “File –> New –> Project”.
Use the “WPF Application” template to create a project with the name “ChatGUI” inside a new solution named “Chat”, as seen here:
The WPF Application template will open to a GUI builder (“designer mode” view) of a file called MainWindow.xaml [see “XAML Overview” ]. Click the “Toolbox” tab on the left side of the screen to expand the view of GUI elements, and drag two TextBox controls onto the screen. We’ll use one of the TextBox widgets to be the display screen where we see all the text written by our friends during a chat session, and we’ll use the other TextBox as the entry field for adding to the chat conversation. Rather than adding a submit button, we’ll just pay attention to the Enter key when a user is typing in the entry field. There are also plenty of other interesting controls, and we may come back in a later post to demonstrate some of them, like the RichTextBox for display formatted text with colors and images interspersed [see “WPF Controls” ].
Next, in the XAML editing pane on the bottom portion of the screen, let’s adjust the size, placement, and names of our TextBox elements, by changing the XAML code to read:
If you type this in manually (as opposed to cutting and pasting the whole thing), you’ll notice the editor’s Intellisense features helping you. For example, fields like HorizontalAlignment have a finite number of values that you can choose from. Similarly, there are a predefined set of events that a TextBox can respond to. We’ve chosen to bind the “KeyDown” event on the “textBoxEntryField” to a new method, and in fact I even let Visual Studio choose the name of that method for me (as you type KeyDown=””, a drop-down box appears, allowing you to select <New Event Handler>). Now click on the MainWindow.xaml.cs tab. This brings us to the C# “code-behind” for the GUI. Notice that an empty textBoxEntryField_KeyDown method has already been created for us in the MainWindow class (you can also get to this by highlighting “textBoxEntryField_KeyDown” in the XAML editor window, clicking the right mouse button, and choosing “Navigate to Event Handler”).
At this point, you’ve already created enough code to build the application and pop up a GUI window. Try it out by hitting F5, and confirm that everything builds without errors, and when it runs a new window appears that looks something like this:
Assuming that worked, great. Now kill your application, either by closing the window or by hitting shift-F5 back in Visual Studio.
By the time we’re done, our MainWindow.xaml.cs code will have three methods: the MainWindow constructor, the textBoxEntryField_KeyDown event handler, and a DisplayMessage method that we’ll use for displaying text in the textBoxChatPane widget. We’ll also have one private member variable that will act as a handle to an object that represents all the back-end functionality. But before we go any further on the GUI implementation, let’s switch gears and create the back-end system.
In the Solution Explorer pane, right-click the “Solution ‘Chat’” line, and go to “Add –> New Project… –> Class Library” and call the new project ChatBackend.
This project is going to contain all the communication code, and we could have used one of the WCF templates instead of just a generic C# class library – these are worth playing around with, and are perfect for creating a client/server app, but none of them happen to be exactly suited for the peer-to-peer configuration we’re going to create, so we’ll do it by hand.
In this project, we’ll end up with two C# files: the IChatBackend interface that defines the set of methods to be supported by a backend implementation, and the ChatBackend class with the actual logic. First we’ll create the interface. Right-click on “ChatBackend” in the Solution Explorer pane, and select “Add –> New Item –> Interface” and call it IChatBackend.cs.
Before you start typing in code for IChatBackend.cs, you should add the necessary references. We’ll be using WCF libraries, and you will need to specify references to System.ServiceModel and System.Runtime.Serialization. In the Solution Explorer pane, right-click on the References node under the ChatBackend project. Go to “Add Reference…”, click on the .NET tab, and add System.ServiceModel, then repeat the process for System.Runtime.Serialization.
In this code, we’ll say that any class which implements the IChatBackend interface has to define two methods: DisplayMessage and SendMessage. You can think of the usage of DisplayMessage in a remote procedure call sort of way – our friends on the peer-to-peer network will call our DisplayMessage method when they want us to display something. We will use our own SendMessage method the call the DisplayMessage methods owned by all of our friends.
We’ll say that DisplayMessage does not return any values, and is a OneWay communication mechanism (we tell our friends to display something, but they don’t have to respond).
In this file, we’ll also define a class called CompositeType, which is capable of holding two string values (a username and a message), and we’ll say that the DisplayMessage method should always be called with one of these CompositeType objects. This is not strictly necessary – we could have simply defined DisplayMessage to take two strings – but when you start to build on this application to send more complicated data objects over the network, the CompositeType will come in handy.
Lastly, we’ll define a delegate type DisplayMessageDelegate. This exists to help us separate the GUI code from the application logic and communication code. The idea is that the GUI will have some mechanism for showing a message on the screen, but the backend shouldn’t have to be aware of the implementation details. When we start up the system, the GUI code will use delegates to pass a function handle to the backend, which can be called whenever the backend wants the GUI to display a message to the user.
All of the code described above is shown here in the listing for IChatBackend.cs:
The next step is to create the implementation of our ChatBackend. When we created the ChatBackend project, it generated an empty Class1.cs file, which you can “File –> Save Class1.cs As…” ChatBackend.cs to rename it.
The ChatBackend class will have the following methods inside it:
Here’s the code for the implementation:
Now that we have the ChatBackend in place, let’s go back to the GUI code to wire everything together.
The GUI contains code that will be instantiating a ChatBackend object and calling its methods, so the ChatGUI project will need to contain a reference to the ChatBackend project. Specify this by right-clicking the References item under the ChatGui project in the Solution Explorer. Select “Add Reference…” and in the Projects tab, select ChatBackend.
Now start editing MainWindow.xaml.cs under the ChatGui project. We’ll need a private member variable to keep a reference to a ChatBackend object, and we’ll need to fill out the constructor, the event handler and the DisplayMessage methods.
Here’s the resulting source code:
This is all the C# source code that we’ll need for our application, but we have on last missing piece, which is that we need to create a configuration file that will tell WCF how to behave. For background information on the configuration file we’re about to create, see “Windows Communication Foundation Configuration Schema” and “Configuration Editor Tool (SvcConfigEditor.exe)” .
In Visual Studio, go to “Tools –> WCF Service Configuration Editor”. This will launch the configuration editor in a new window. Select “File –> New Config” to bring up an empty configuration, which should look something like this:
Select “Create a New Service” from the right-hand pane.
The “Service type” should be ChatBackend.ChatBackend
The “Service contract” should be ChatBackend.IChatBackend
Select “Peer to Peer” as the communication mode.
The address for the endpoint should be: net.p2p://Chat
Next, click on “Endpoint: (Empty Name)” and give the endpoint the name “Chat”
At this point, you should save the configuration into <your projects directory>\Chat\ChatGUI\App.config (where <your projects directory> is typically something like C:\Users\username\Documents\Visual Studio 2010\Projects).
Now, continuing in the configuration editor, let’s create a client. Since this is a peer-to-peer application, our program acts as both a service provider and a client for that same service.
In the left-hand Configuration pane, click on “Client”, and then in the right-hand pane, “Create a New Client”. We’ll want to create a client based on the service configuration we’ve already created, so in the “Generate a client config from the config of the service” field, browse to this same configuration file that you just saved, and click Next.
There should be just one service endpoint to select (the ChatBackend.ChatBackend endpoint), and name your Client configuration ChatEndpoint.
Last, we’ll need to define the bindings. Click on “Bindings” in the left-hand pane, followed by “Create New Binding” and select the netPeerTcpBinding type. Change the binding configuration name to be “Wimpy” (because we’ll start with something completely unsecure… later we can come back and require different varieties of authentication).
On the Security tab for this binding, choose Mode: None. Then in the left-hand pane, under Bindings –> Wimpy –> resolver, click “resolver” and set Mode to be Pnrp.
Now go back to “Services –> ChatBackend.ChatBackend –> Endpoints –> Chat” in the left-hand pane and set BindingConfiguration to be “Wimpy”.
Do the same for “Client –> Endpoints –> ChatEndpoint –> BindingConfiguration”
Finally, save and close the Configuration window.
Next, in the Solution Explorer, right-click on the ChatGUI project, select Add Existing Item, and add the App.config file to the project (you’ll have to change the file filters to allow all file types in order to browse to it).
Double-click the App.config file in order to double-check the work that was done by the configuration editor. You should see the following XML code. If it isn’t quite right, you can always fix it up by hand:
Now we’re done!
Let’s build and run the final program.
To do so, hit F5 in Visual Studio.
Since the program will try to establish a service that listens on a port, you’ll see a security dialog like the following:
Click the “Allow Access” button.
Then, because a chat application isn’t any fun without at least two instances, run another copy. you can browse to the program and run it by double-clicking <your projects folder>\Chat\ChatGUI\bin\Debug\ChatGUI.exe
And we have two chat windows open that can talk to each other: