Introduction
The first question is what is Synchronized Distributed System? I'm not sure of the official term. I named it from my understanding. The typical application is stock trade software. If you have experience on stock investment, you will like the user interface in front of you could display all the changing information of the stock you are staring at just in time. But to be honest, I hate Chinese stock market as well as the real estate market.
In this part, we are going to simulate a similar scenario: Inventory Monitor. I design two persons whose names are Will, Mike respectively. They are in different offices. Will and Mike are all responsible for inventory management. If Will adds one product into system, Mike should be able to see the new product. If Mike changes the inventory number, Will is able to see the change as well.
Background
My final purpose is to design a service bus mechanism based on WCF. This article would be the first part.
Using the Code
It is actually not difficult to make a remote call. The key point to make a Synchronized system is to implement subscription from server. To implement subscription, we need to user duplex connection
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IMessageSenderCallBack))]
public interface IMessageSender
{
[OperationContract(IsOneWay = false, IsInitiating = true, IsTerminating = false)]
void Init();
}
[ServiceContract]
public interface IMessageSenderCallBack
{
[OperationContract(IsOneWay = true)]
void SendMessage(Message message);
[OperationContract(IsOneWay = true)]
void SendHeartBeat();
}
The subscription in WCF is a little bit like what we called observer design pattern.
SessionMode = SessionMode.Required
Help to keep the connection between server and client
CallbackContract = typeof(IMessageSenderCallBack))
Open the interface to client to enable server to call the method implemented IMessageSenderCallBack
[OperationContract(IsOneWay = true)]
indicate server will call the client methods without waiting for the return value.
From the client side, we create a class implemented from IMessageSenderCallBack
. In our case, the main form is the class.
*Now we draw the scenario on how to change inventory and let other clients know the change.
Points of Interest
Event is very important to help you build up the subscription system. On server side, we don't know how to trigger the subscription to multi-client. That is why we have an Init()
method in MessageSender
class. Init()
will register those events needs to be subscribed.
How to demonstrate the code
- Open SAOT.exe
- Click Confirm to open the service
- Open ClientTest.exe
- Click Confirm to connect the server
- Open another ClientTest.exe instance
- Connect the server as well. Change the name from Will to Mike
- Now you have 2 clients.
Please also read the following articles:
http://www.codeproject.com/KB/WCF/How_to_abstract_WCF.aspx
http://www.codeproject.com/KB/WCF/WCF_ESB.aspx