The legendary WCF: group chat program

Source: Internet
Author: User

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. This example uses the following knowledge point: To carry the WCF Service in the process. Session usage. 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. [Csharp] [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 );} [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 End sessions, respectively, in this way, a service class will be instantiated every time a client connection is connected (as mentioned in the previous article), so that each client can maintain 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. [Csharp] [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) ;}} [ServiceBehavior (IncludeExceptionDetailInFaults = true, InstanceContextMode = InstanceContextMode. perSession)] public class MyService: IService {public static Dict Ionary <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. valu Es. 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. [Csharp] static void Main (string [] args) {Console. title = "WCF Server Side"; 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 authentication binding is required. security. mode = SecurityMode. none; // Add the end point host. addServiceEndpoint (typeof (IService), binding, "net. tcp: // 127.0.0.1: 1736/channel "); // yuan Data 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 () ;}} static void Main (string [] args) {Console. title = "WCF Server Side"; 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 authentication binding is required. security. mode = SecurityMode. N One; // Add the 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 () ;}} the endpoint uses net. tcp binding. 4. Implement callback protocols on the client. First, reference the service on the client, and then implement the callback protocol interface. [Csharp] 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;} 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) ;}// the event public event EventHandler <CallbackRecEventArgs> MessageReceived;} also has an event parameter class. [Csharp] 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 ;}} 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. [Csharp] cb = new MyCallBack (); cb. MessageReceived + = callback; cb = new MyCallBack (); cb. MessageReceived + = cb_MessageReceived; [csharp] view plaincopyprint? 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);} void cb_MessageReceived (object sender, CallbackRecEventArgs e) {MessageEnt msg = new MessageEnt (); msg. nickName = e. nick; m Sg. 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.

 

 

Related Article

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.