A couple posts ago I was doing some experimentation with TCPClient and TCPServer. The bulk of my testing was done by creating a simple chat application. After that I decided I wanted to figure out how to do the same thing using WCF. The goal was to have an application that could talk directly with the same application on another computer using WCF.
First I needed a contract:
[ServiceContract(Namespace = "http://WCFTest")]
public interface IChat
{
[OperationContract(IsOneWay = true)]
void SendChat(string message);
}
And an implementation of the contract:
public class ChatService : IChat
{
public static ChatWindow chatWindow;
public void SendChat(string message)
{
chatWindow.AppendText(message);
}
}
The static field is there because every time a request comes in, a new instance of ChatService is created by the host. This is important to note, because with the default behavior you cannot expect state to stick around between requests.
Now I could create a service host and open my chat window:
static void Main()
{
var window = new ChatWindow();
ChatService.chatWindow = window;
try
{
host = new ServiceHost(typeof(ChatService));
host.Open();
}
catch (CommunicationException exception)
{
window.AppendText(exception.Message);
host.Abort();
}
window.ShowDialog();
}
Next I needed to add the client code:
[ServiceContractAttribute(Namespace = "http://WCFTest",
ConfigurationName = "WCFTest.IChatClient")]
public interface IChatClient
{
[OperationContract(IsOneWay = true,
Action = "http://WCFTest/IChat/SendChat")]
void SendChat(string message);
}
public partial class ChatClient
: ClientBase<IChatClient>, IChatClient
{
public ChatClient()
{
}
public void SendChat(string message)
{
base.Channel.SendChat(message);
}
}
This allowed my application to create a client, and make calls to the WCF interface:
private void sendButton_Click(object sender, EventArgs e)
{
var client = new ChatClient();
client.SendChat(chatMessage.Text);
chatMessage.Text = "";
}
The app.config for this application contains a services and client section, with endpoints defined in both. The client section’s endpoint defines the address of the computer to connect to, but with a little more code it could get addresses for computers dynamically and connect to multiple computers.
In my TCPClient/TCPServer experiment, I was trying to send delegates across the wire. One of the cool thing about WCF is that I wouldn’t need to do that anymore, the contract just needs to define the methods that can be called.
