In this lesson, you will create a simple chat-style server to which multiple clients can connect. When one client sends a string message to the server, the server forwards the message to all registered clients that have not been specifically excluded.  You should note that a real chat application would be based on a more scalable and flexible design to connect client and servers, such as a publish-and-subscribe design.

Creating a Simple Chat Server Using Delegates

In this exercise, you will implement a simple chat server and clients by using delegates. 

Scenario

Each client will register a delegate with the server. Then, when a client sends a message to the server, the server forwards the message to all specified clients. This implementation uses delegates as a callback mechanism.

Exercise

1. Create a Visual Studio .NET project

  • Open Visual Studio .NET and create a new C# Console Application project named chat1

2. Create the chat server class

  1. Create the chat server class and name it DChatServer.
  2. Declare within the DChatServerclass a delegate that will be used to invoke the callback function in the client when a chat message arrives.
    1. Name the delegate OnMsgArrived.
    2. Declare this delegate public and reflect the callback function’s signature. The callback’s signature is a void return value with a single argument of type string (you can call this string “message”).
  3. Define a field to store the connected client’s delegates by performing the following steps.
    1. Name the field onMsgArrived.
    2. Make the field a private static reference to the type of the delegate, OnMsgArrived.
  4. Declare a private constructor for DChatServer so that it cannot be instantiated externally.
  5. Define the method that will be called by a client to connect that client to the server by performing the following steps.
    1. Name the method ClientConnect.
    2. Declare the method public static void.
    3. Include an argument of type OnMsgArrived.
    4. Create the method’s implementation by using the delegate’s += to add this new delegate to the delegate stored in the onMsgArrived invocation list.
  1. Define a method that will be called by a client to disconnect that client from the server by performing the following steps.
    1. Name the method ClientDisconnect.
    2. Declare the method public static void.
    3. Declare the method so that it has the same signature as ClientConnect.
    4. Create the method’s implementation by using the delegate’s -= to remove the delegate from the onMsgArrived invocation list.
  1. Define a method that will send a specified message to the connected clients, with the possible exception of one client, by performing the following steps.
    1. Name the method SendMsg.
    2. Declare the method public static void.
    3. Declare the method so that it takes one argument: a string argument for the message. This is the message that server sends to all the clients.
    4. Create the method’s implementation.

To invoke a delegate you need to run onMsgArrived(msg);

3. Create the chat client class

  1. Create the chat client class and name it DChatClient.
  2. Implement within the DChatClientclass a callback method that the server will invoke by a delegate when the server receives a chat message.
    1. Name the method onMsgArrived.
    2. Declare the method private void.
    3. Declare the method so that it takes a single string argument.
    4. Create the method’s implementation so that it prints the name of the client along with the string argument to the console.
  3. Add a constructor that will receive the name of the client as a parameter and connect the client with the server.
    1. Declare the constructor so that it takes a string argument that represents the client’s name.
    2. Create the constructor’s implementation.
      1. Store the client’s name in a private field.
      2. Connect the client to the server by calling the server’s ClientConnect method.  DChatServer.ClientConnect(…) ß fill in this yourself!
  4. The call’s argument should be an instance of the delegate type DChatServer.OnMsgArrived that was instantiated with the client’s callback method: onMsgArrived.

4. Create the program’s main entry point

  1. Name the class that contains the program’s standard Main entry point, Application.
    1. Typically, a Visual Studio .NET project creates the class with the Main entry point for you. You may only need to rename this class.
  2. Write to the console a line of text to indicate that the program is starting.
  3. Instantiate three DChatClient objects, passing the client names .1., .2., and .3. to the constructor.
  4. Send a message to the server by invoking the static method SendMsg of the DChatServer. The message should be sent to all clients.
  5. Write to the console a line of text to indicate that the program is finished.

5. Compile and test the program

  • Build the program and run it.

The output should resemble the following:

Demo start: Delegate Chat Server.
Msg arrived (Client 1): Hi to all clients
Msg arrived (Client 2): Hi to all clients
Msg arrived (Client 3): Hi to all clients
Msg arrived (Client 1): There is a message from client1
Msg arrived (Client 2): There is a message from client1
Msg arrived (Client 3): There is a message from client1
Demo stop: Delegate Chat Server.

HOME WORK:

Creating a Simple Chat Server Using Events

In this exercise, you will implement a simple chat server and clients by using events and delegates. This implementation uses the event keyword, which hides some of the low-level code details associated with delegates and prevents clients from accessing or invoking the delegates of other clients. 

Scenario

Each client will connect with the server’s “on message arrived” event. Then, when one client sends a string message to the server, the server forwards the message to all specified connected clients.

1. Access the chat1 Visual Studio .NET project

  • Open Visual Studio .NET and open the project named chat1, which you created in Exercise 1. Open the previously created C# source file and perform the following procedures.

2. Create the event-based chat server class

  1. Create a new chat server class and name it EChatServer.
  2. Declare within the EChatServerclass a delegate that will be used to invoke the callback function in the client when a chat message arrives.
    1. Name the delegate OnMsgArrived.
    2. This delegate should be declared publicand reflect the callback function’s signature.
      1. The callback’s signature is a void return value with a single argument of type string.
  3. Declare an event for the OnMsgArriveddelegate type.
    1. Name the event onMsgArrived.
    2. Declare the event public static.
  4. Define a method that will send a specified message to the connected clients, with the possible exception of one client.
    1. Name the method SendMsg.
    2. Declare the method public static void.
    3. Declare the method so that it takes two arguments: a string argument for the message and an object argument for the excluded client.
    4. Create the method’s implementation.
      1. If the excluded client argument is null, invoke the multicast delegate to send the message to all of the clients.
      2. If the excluded client argument is not null, iterate through the onMsgArrived delegate’s invocation list and invoke only those delegates that do not match the excluded client argument.
    5. The ClientConnect and ClientRemove methods from DChatServer are NOT included!

3. Create the event-based chat client class

  1. Create a new chat client class and name it EChatClient.
  2. Implement within the EChatClientclass a callback method that the server will invoke by a delegate when the server receives a chat message.
    1. Name the method onMsgArrived.
    2. Declare the method private void.
    3.          Declare the method so that it takes a single string argument.
    4. Implement the method so that it prints the name of the client, together with the string argument, to the console.
  3. Add a constructor that will receive the name of the client as a parameter and connect the client with the server.
    1.          Declare the constructor so that it takes a string argument that represents the client’s name.
    2. Create the constructor’s implementation.
    3. Store the client’s name in a private field.
    4. Connect the client to the server by using the += operator to add a new delegate instance to the EChatServer’s event. The += operator’s right operand should be an instance of the delegate type EChatServer.OnMsgArrived that was instantiated with the client’s callback method, onMsgArrived.

4. Extend the program’s main entry point by performing the following procedures

  1. Write to the console a line of text to indicate that the event chat portion of the program is starting.
  2. Instantiate three EChatClient objects, passing the client names “1”, “2”, and “3” to the constructor.
  3. Send a message to the server by invoking the static method SendMsg of the EchatServer. You should send the message to all clients.
  4. Send a second message to all clients except client 2.
  5. Write to the console a line of text to indicate that event chat is finished.

5. Compile and test the program

  • Build the program and run it.

The output should resemble the following:

Demo start: Event Chat Server.
Msg arrived (Client 1): Hi to all clients
Msg arrived (Client 2): Hi to all clients
Msg arrived (Client 3): Hi to all clients
Msg arrived (Client 1): Hi to all clients except client 2
Msg arrived (Client 3): Hi to all clients except client 2
Demo stop: Event Chat Server.

NOTE: The following methods of delegate may be useful:
Delegate.GetInvocationList(), Delegate.Target

Tagged with: C-SharpProgramming
 

One Response to Delegates and Events in C#.NET

  1. vinoli says:

    i need this chat application souce code

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.