Wednesday, February 15, 2012

[Network Programming] Client-Server classes P2 Window Form


Continue from this post: http://zquanghoangz.blogspot.com/2012/02/network-programming-tcplistener-with.html
In this post I will use two classes Client Server in Window Form demo application. But I sure this application have many bugs, because it is an demo. It will give you have some ideas for your exercise. OK, join it.

Application show simply way to chat with client server, you can apply it to all big exercise on your university. I will descirible what I write in project, and how it work with some important node you need remember when custom this code.
Code and video demo in bottom of this post.

1. With Client Server classes you can see in last my post, but I change a litle in Server class. There is a new Event call ClientConnected. It will catch all client connected to server on starting time.
All events in this code:


   1:          #region Events
   2:   
   3:          #region Delegates
   4:   
   5:          public delegate void ReceivedMessageEventHandle(TcpClient client, string message);
   6:          public delegate void ClientConnectedEventHandle(TcpClient client);
   7:   
   8:          #endregion
   9:   
  10:          public event ReceivedMessageEventHandle ReceivedMessage;
  11:          public event ClientConnectedEventHandle ClientConnected;
  12:   
  13:          #endregion


2. Two forms are almost of same functions, we can go to detail:
 - Constructor and events handle
   1:          public FormServer()
   2:          {
   3:              InitializeComponent();
   4:              _isStarted = false;
   5:              _server = new Server();
   6:              _server.ReceivedMessage += server_ReceivedMessage;
   7:              _server.ClientConnected += server_ClientConnected;
   8:   
   9:              _listClientsConnected = new Dictionary<string, TcpClient>();
  10:          }

You can see two events of server will be handle by server_ReceivedMessage, server_ClientConnected. It mean when Server suddenly get message or a client connected to, events will be raise and you can catch it, then write some function you want with data.

Here is code I handle events:
   1:          private void server_ClientConnected(TcpClient client)
   2:          {
   3:              //Add new client to list
   4:              if (!_listClientsConnected.ContainsKey(client.GetHashCode().ToString()))
   5:              {
   6:                  _listClientsConnected.Add(client.GetHashCode().ToString(), client);
   7:   
   8:                  if (InvokeRequired)
   9:                  {
  10:                      lstClients.Invoke(new Action(delegate { lstClients.Items.Add(client.GetHashCode().ToString()); }));
  11:                  }
  12:              }
  13:          }
  14:   
  15:          private void server_ReceivedMessage(TcpClient client, string message)
  16:          {
  17:              if (InvokeRequired)
  18:              {
  19:                  txtReceivedMessages.Invoke(
  20:                      new Action(
  21:                          delegate { txtReceivedMessages.Text += client.GetHashCode() + ": " + message + Environment.NewLine; }));
  22:              }
  23:          }

You can see two classes Client Server, I am using Thread, then if you want to across-thread, you will invoke thread using code above (comment invoke thread you will see exception raised). When a client connected to server, It will store on a dictionary collection with key is a hash code, and show in on screen by all hash code to list box. When server recieved message, It will show it to append to text box. Form client will be same with server.

Send message will quite different bettween client and server. Client is very simple because it will send to only one server, what it connect to. In difference, server have many client connect to, we are have a list client store in _listClientsConnected. So, user need to choose one of them and send. Function will like this:
   1:        private void btnSend_Click(object sender, EventArgs e)
   2:          {
   3:              if (lstClients.Items == null || lstClients.Items.Count < 1 || lstClients.SelectedItem == null) return;
   4:   
   5:              txtReceivedMessages.Text += "Me to" + lstClients.SelectedItem + ": " + txtMessage.Text + Environment.NewLine;
   6:              _server.SendMessage(_listClientsConnected[lstClients.SelectedItem.ToString()], txtMessage.Text);
   7:          }

That will send message to an client you choose.
As I mention, this application use thread. Don't forget, we need close it by this function:
   1:          private void FormServer_FormClosing(object sender, FormClosingEventArgs e)
   2:          {
   3:              Environment.Exit(0);
   4:          }
It will close all working threads.
I hope you can easy to understand this application and custom it like you want to your exercise.
Here is ...
    Source: http://www.mediafire.com/?sgn3y93utpe21rz
    Video: http://www.youtube.com/watch?v=4tBstBvAUUo&feature=youtu.be
Thank for read!

No comments:

Post a Comment