Saturday, August 15, 2009

Global Text Chat Room Application using C#.Net Programming - Remoting technology 5/6

ß Read Previous

Send message to server:
When user type some message and press on ‘Send’ button or just press ‘Enter’ button then client application try to send message to server. To do it client call the below method –
private void SendMessage()
{
if (remoteObj != null && txtChatHere.Text.Trim().Length>0)
{
remoteObj.SendMsgToSvr(yourName + " says: " + txtChatHere.Text);
txtChatHere.Text = "";
}
}
Here client application in invokes the “SendMsgToSvr()” method of server. Let’s see the method what doing-
public void SendMsgToSvr(string chatMsgFromUsr)
{
hTChatMsg.Add(++key, chatMsgFromUsr);
}
Wow! This is very small code. Actually this is adding the users’ message to another collection. I have used for this collection of HashTable type, you may use any other collection type to store string data.
See here has one counter ‘key’ which is incrementing by one. This is the counter which is maintaining the chat message number. It will help us to get chat message from server.
Receive Message from Server:
Ok friend, next look at how data are getting from server –
In chat room a timer always fires, which try to get message from server and current available user in server. Here below codes plays in Client side –
private void timer1_Tick(object sender, EventArgs e)
{
if (remoteObj != null)
{
string tempStr = remoteObj.GetMsgFromSvr(key);
if (tempStr.Trim().Length > 0)
{
key++;
txtAllChat.Text = txtAllChat.Text + "\n" + tempStr;
}
ArrayList onlineUser = remoteObj.GetOnlineUser();
lstOnlineUser.DataSource = onlineUser;
skipCounter = 0;
if (onlineUser.Count < 2)
{
txtChatHere.Text = "Please wait untill atleast two user join in Chat Room.";
txtChatHere.Enabled = false;
}
else if(txtChatHere.Text == "Please wait untill atleast two user join in Chat Room." && txtChatHere.Enabled == false)
{
txtChatHere.Text = "";
txtChatHere.Enabled = true;
}
}
}
Here client invokes “GetMsgFromSvr()” method to get message, with parameter key. The codes of the method are –
public string GetMsgFromSvr(int lastKey)
{
if (key > lastKey)
return hTChatMsg[lastKey + 1].ToString();
else
return "";
}
The server just takes the key as last-key of user’s message and uses it in Chat message collection to fetch the next chat message, after that the message return to the client.
To online user client application invokes “GetOnlineUser()” method, lets see what happen in server side within the method.
public ArrayList GetOnlineUser()
{
return alOnlineUser;
}
So this method returns the user collection object which was created in “JoinToChatRoom()” method.

Read Next à

No comments: