Legendary WCF (13): group chat program

Source: Internet
Author: User
The legendary WCF (1): Is this hard to learn?The legendary WCF (2): What about service agreements?Legendary WCF (3): multiple protocolsLegendary WCF (4): send and receive SOAP HeadersLegendary WCF (5): data protocols ()Legendary WCF (6): data protocols (B)Legendary WCF (7): "one-way" & "two-way"Legendary WCF (8): Play with message protocolsLegendary WCF (9): stream and file transferLegendary WCF (10): message interception and tamperingThe legendary WCF (11): Session)The legendary WCF (12): What is the use of server callback?Legendary WCF (13): group chat programThe legendary WCF (14): WCF can also be used as a chat program.

 

 

A lot of key knowledge has been blown up before. In order to make comprehensive use of them, today, we will make a group chat application, just like the QQ group, one server, and N clients, after the server is running, each client automatically connects to the server to generate a session when it starts. As long as any client sends messages to the server, the server sends messages to all clients.

Let's take a look at how to replace socket with WCF.

 

The following knowledge points are used in this example:

  1. It carries the WCF Service in the process.
  2. Session usage.
  3. Callback.

In the following illustration, I will not paste all the code. After all, it is a little long. I only release the important part, and then I will upload the source code to [Resource ].

I. Service Agreements and callback agreements.

[Servicecontract (callbackcontract = typeof (icallback), sessionmode = sessionmode. Required)]
Public interface iservice
{
[Operationcontract (isoneway = true, isinitiating = true, isterminating = false)]
Void begin ();
[Operationcontract (isoneway = true)]
Void sendmessage (string Nick, string MSG, datetime sendtime );
[Operationcontract (isoneway = true, isinitiating = false, isterminating = true)]
Void end ();
}

Public interface icallback
{
[Operationcontract (isoneway = true)]
Void sendtoclients (string Nick, string MSG, datetime sendtime );
}

The begin and end Methods start and terminate sessions respectively. In this way, each client connection is instantiated as a service class (as mentioned in the previous article ), this ensures that each client maintains a session with the server.

Messages sent to the server include the user's nickname, message content, and sending time. The methods in the callback protocol are also these parameters, but the difference is that the service protocol is the client that calls the server, while the callback is the server that calls the client.

 

2. Implement the service class.

[Servicebehavior (includeexceptiondetailinfaults = true, instancecontextmode = instancecontextmode. persession)]
Public class myservice: iservice
{
Public static dictionary <string, icallback> clientcallbacks = new dictionary <string, icallback> ();
Public void begin ()
{
String sessionid = operationcontext. Current. sessionid;
Icallback cb = operationcontext. Current. getcallbackchannel <icallback> ();
Myservice. clientcallbacks [sessionid] = CB;
}

Public void sendmessage (string Nick, string MSG, datetime sendtime)
{
Foreach (icallback C in myservice. clientcallbacks. Values. toarray ())
{
If (C! = NULL)
{
C. sendtoclients (Nick, MSG, sendtime );
}
}
}

Public void end ()
{
String sessionid = operationcontext. Current. sessionid;
If (myservice. clientcallbacks. containskey (sessionid ))
{
Myservice. clientcallbacks. Remove (sessionid );
}
}
}

I originally wrote comments in the code, but I just deleted them. I hope you can understand the code without comments.

In the class, a static dictionary <string, icallback> is declared. This is a dictionary. I guess that static variables are class-based and have nothing to do with instances, we can regard it as global data and save all access client callbacks in the dictionary set. Because the ID of each session is unique, it is better to use sessionid as the key.

A. When the begin method is called, we store the session ID and callback of the passed client into the dictionary. When the end method is called, the session is terminated, in this case, the corresponding session ID and callback are deleted from the dictionary.

B. When the sendmessage method is called, retrieve all callbacks from the dictionary and pass the received parameters to the callback method. After the callback method is called, the messages are forwarded to all connected clients.

This enables group chat.

 

3. Create a server.

Static void main (string [] ARGs)
{
Console. Title = "WCF server ";
Uri baseaddr = new uri ("http: // 127.0.0.1: 2713/wcfsv ");
Using (servicehost host = new servicehost (typeof (myservice), baseaddr ))
{
Nettcpbinding binding = new nettcpbinding ();
// No security verification is required
Binding. Security. mode = securitymode. None;
// Add an endpoint
Host. addserviceendpoint (typeof (iservice), binding, "net. TCP: // 127.0.0.1: 1736/channel ");
// Metadata
Servicemetadatabehavior MB = new servicemetadatabehavior ();
MB. httpgetenabled = true;
MB. httpgeturl = new uri ("http: // 127.0.0.1: 87/WSDL ");
Host. description. behaviors. Add (MB );
Host. Opened + = (source, ARG) =>
{
Console. writeline ("the service has been started. ");
};
// Open the service
Try
{
Host. open ();
}
Catch (exception ex)
{
Console. writeline (ex. Message );
}

Console. readkey ();
}
}

Because TCP supports sessions and fast transmission, the endpoint is bound with net. TCP.

 


4. Implement callback protocols on the client.

First, reference the service on the client, and then implement the callback protocol interface.

Public class mycallback: Ws. iservicecallback
{
Public void sendtoclients (string Nick, string MSG, datetime sendtime)
{
If (this. messagereceived! = NULL)
{
Callbackreceventargs Arg = new callbackreceventargs (Nick, MSG, sendtime );
This. messagereceived (this, ARG );

}
}

// Event
Public event eventhandler <callbackreceventargs> messagereceived;
}

There is also an event parameter class.

Public class callbackreceventargs: eventargs
{
String _ Nick, _ MSG;
Datetime _ time;

Public callbackreceventargs (string NK, string M, datetime T)
{
_ Nick = NK;
_ MSG = m;
_ Time = T;
}

Public String Nick
{
Get {return _ Nick ;}
}
Public String messagecont
{
Get {return _ MSG ;}
}
Public datetime sendtime
{
Get {return _ time ;}
}
}

Because the method in the callback is used by the server, remember that it is not called by the client. When the customer wants to listen to the method called in time, they can use the event. When the callback method is called, the event will be triggered, and another event is triggered, it can define the processing method in other classes.

For example.

CB = new mycallback ();
CB. messagereceived + = cb_messagereceived; void cb_messagereceived (Object sender, callbackreceventargs E)
{
Messageent MSG = new messageent ();
MSG. Nickname = E. Nick;
MSG. Message = E. messagecont;
MSG. Time = E. sendtime;
If (E. Nick = mynickname)
{
MSG. ISME = true;
}
Else
{
MSG. ISME = false;
}
This. datasource. Add (MSG );

} Others can refer to the source code we uploaded later.

Let's take a look at the running results.

 

 

 

Haha, how is it?

Is this worse than socket?

 

 

 

 

Turn to it

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.