Because duplex realizes the function of two-way communication between client and server, I realize a simple chat room program to show the characteristics of duplex. After reading this example, a friend asked a question, "How do I get the server to send a message to a specified client?" "Happily, the friend said in a later mail that the problem has been solved, thinking is to use the Singleton object to save the client session." Although there are some strange problems, but finally a way of thinking.
My ideas are similar, requiring the service side to maintain a dictionary collection to hold the client's information. When a server sends a message, it can identify the client that meets the criteria by looking for the Dictionary object. When I was still thinking about whether the way to solve the problem, I stumbled on the WCF official website to use duplex to implement the chat room sample.
Read the example code carefully, I suddenly found myself in thinking about programming, and did not understand the core value of WCF, that is, "services." As a technical framework for implementing the SOA architecture, WCF's most important feature is its ability to define and deliver services. Take a chat room program as an example, although the server will participate in the interaction of the message, but should not participate in the chat. In other words, the role tasks for the client and server are different. You can see the difference between the two by using a use case diagram:
Figure 1 The correct use case diagram
Diagram two wrong use case diagram
It is clear that the "service" as the core of the program structure, we can better use WCF, customize their own services, clear the boundaries of services, define the format of good news. Although a chat room program does not embody the core spirit of SOA, it is essential to establish a service-oriented mindset. As we begin object-oriented programming, we need to establish object-oriented thinking.
The realization of the chat room program is mainly realized by duplex, which utilizes the MulticastDelegate and asynchronous invocation. The service interface is defined as follows:
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IChatCallback))]
interface IChat
{
[OperationContract(IsOneWay = false, IsInitiating = true, IsTerminating = false)]
string[] Join(string name);
[OperationContract(IsOneWay = true, IsInitiating = false, IsTerminating = false)]
void Say(string msg);
[OperationContract(IsOneWay = true, IsInitiating = false, IsTerminating = false)]
void Whisper(string to, string msg);
[OperationContract(IsOneWay = true, IsInitiating = false, IsTerminating = true)]
void Leave();
}