Click here to Skip to main content
15,867,209 members
Articles / Operating Systems / Windows
Article

Instant Messaging / Chat using Remoting, for LAN

Rate me:
Please Sign up or sign in to vote.
4.87/5 (29 votes)
13 Jul 2006CPOL3 min read 316.1K   18.5K   96   122
Instant messaging / chat using Remoting, for LAN.

Sample Image - ChatMasala.gif

Introduction

Communication between two applications running on different (or same) systems in a Local Area Network is not a luxury, but a necessity. The .NET framework provides various solutions for solving this - Remoting, Socket Programming (TCP/UDP), Web Services etc. I will be using Remoting in my application because I believe it is the most powerful tool.

I have developed an Instant Messaging system. The system consists of a server application, a client application, and a library which is used by both the server and the client.

Without further ado, let me start explaining the code.

Using the code

Class library

The class library consists of the interface IServer and some other classes. The interface IServer dictates the functionality of the server. This information is used by the client to call the methods of the remote object.

C#
public interface IServer
{
    bool SignUp(string username,string password);
    bool ChangePassword(string username,string curPassword,string newPassword);
    bool SignIn(string username,string password,bool visible);
    bool SignOut(string username);        
    
    bool IsVisible(string username);
    bool AddContact(string username,string contact);
    bool RemoveContact(string username,string contact);
    ArrayList GetContacts(string username);
    
    bool Send(string from,string to,string message);
    LetterReceive Receive(string to);
    ArrayList ReceiveOffline(string to);
}

LetterReceive is a class containing two string variables, from and message, and a few properties. It is very straightforward, hence I choose not to give its code.

Server

I will first explain the server class code, and once we are finished with it, I will explain the Remoting part. We will first take a look at the class hierarchy.

At the top of the pyramid, is the class Server. The Server uses the class Letter to store messages. The Server uses an object of class Database to store information which needs to persist between machine shutdowns. This includes account information and offline messages. The class Database uses the class AccountField to store information like password and contacts for a particular user. The class Database uses the class Letter to store offline messages.

We will start with the class AccountField, at the bottom of the hierarchy. Here is the code for it:

C#
[Serializable]
class AccountField
{
    internal string password;
    internal bool isLoggedIn;
    internal bool visible;
    internal ArrayList contacts;
    
    public AccountField(string password,bool isLoggedIn)
    {
        this.password=password;
        this.isLoggedIn=isLoggedIn;
        contacts=new ArrayList();
    }
}

The class Letter has three string variables, from, to, message.

The class Database is quite simple. I will show here part of its code. The rest would be easy to guess. The Hashtable and database are used to store account information as can be seen in the method Add. It also has methods, Load and Save to load and save its instance to disk. The technique used is serialization.

C#
[Serializable]
class Database
{
    //Fields        
    private Hashtable database;
    internal ArrayList offlineMessages;
    
    //Constructor
    public Database()
    {
        database = new Hashtable();
        offlineMessages=new ArrayList();
        Load();
    }
    
    //Methods
    internal bool Add(string username,string password)
    {
        if(database.Contains(username))
            return false;
        database.Add(username,new AccountField(password,false));
        return Save();
    }
    .
    .
    .
}

Let us come to the class Server. As can be seen, Server has inherited from the interfaces IServer and MarshalByRefObject (to enable Remoting). Once again, I will be show only the more important parts of the class declaration.

C#
public class Server : MarshalByRefObject, ChatMasalaLib.IServer
{
    Database database = new Database();
    ArrayList letters = new ArrayList();
    
    //Constructor
    public Server()
    {
        database.Load();
    }
    public bool Send(string from,string to,string message)
    {
        if(database.ContactExists(to)==false)
            return false;

        if(database.IsLoggedIn(to))
            letters.Add(new Letter(from,to,message));
        else
        {
            database.offlineMessages.Add(new Letter(from,to,message));
            if(database.offlineMessages.Count>maxOfflineMessages)
            {
                database.offlineMessages.RemoveAt(0);
            }
            Console.WriteLine(database.Save());
        }
        return true;
    }
    public LetterReceive Receive(string to)
    {
        int length = letters.Count;
        for(int i =0;i < length;i++)
        {
            if(((Letter)letters[i]).To==to)
            {
                LetterReceive lr = new LetterReceive(
                    ((Letter)letters[i]).Message,((Letter)letters[i]).From);
                letters.RemoveAt(i);
                return lr;
            }
        }
        return new LetterReceive("","");
    }    
    public bool SignUp(string username,string password)
    {
        return database.Add(username,password);
    }
    .
    .
    .
}

Now, we come to the Remoting part. This actually enables the communication between the server and the client.

C#
HttpChannel channel = new HttpChannel(8080);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.RegisterWellKnownServiceType(Type.GetType("Temporary_Server.Server"),
    "Server",WellKnownObjectMode.Singleton);

Client

Enough coding, let's get into action. Here is the client explained. I would first describe the Remoting initialization code.

C#
HttpChannel channel = new HttpChannel();
ChannelServices.RegisterChannel(channel);

string hostIP = "127.0.0.1";
MarshalByRefObject obj = (MarshalByRefObject)RemotingServices.Connect(
    typeof(IServer),"http://"+hostIP+":8080/Server");
server=obj as IServer;
(obj as RemotingClientProxy).Timeout=5000;

The tough part is over, now we only have to call the methods of the variable server to work. Here, I have given a few examples:

C#
server.SignIn("AmitDey","Password",true);
server.IsVisible("Boss");
server.Send("AmitDey","Boss","Work complete. Can I go home ?");
//Will receive 1 message if a message exists for user AmitDey
server.Receive("AmitDey");

The client code is huge, distributed into many forms. But, it's all so easy that I am not sharing it with you here. You can check it out in the source code files available at the top of this page.

Points of interest

If you are running the demo project, for your own ease, start the server application first and then the client application.

Here is a pretty ugly problem I faced. Consider the situation where the server is not loaded, but the client application is started. If the client application tries to access any method of the server variable, the client application simply hangs. It does not even cause an exception. In order to simulate a time out, I used this code. I would like to thank my friend Kuldip Saini for this solution.

C#
(server as RemotingClientProxy).Timeout=5000;

I would also like to thank Bipin George Mathew and Kin Tutnik for helping me develop this application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I am a Software Developer from Hyderabad, India

My MSDN Blog

My Windows Phone Apps

Comments and Discussions

 
QuestionStore data into Mysql Database Pin
dearste14-Sep-08 9:50
dearste14-Sep-08 9:50 
GeneralJust un hi Pin
ashwanisihag23-Jul-08 19:23
ashwanisihag23-Jul-08 19:23 
GeneralOnce a client is connected to another client then neither can make another connection until they disconnect or logoff. Pin
ece_manish29-Mar-08 9:29
ece_manish29-Mar-08 9:29 
QuestionProblem in demo as well as need suggestion Pin
Ankana22-Feb-08 19:58
Ankana22-Feb-08 19:58 
GeneralRe: Problem in demo as well as need suggestion Pin
AmitDey22-Feb-08 21:02
AmitDey22-Feb-08 21:02 
Questiondemo Pin
angelicvoice7-Nov-07 2:47
angelicvoice7-Nov-07 2:47 
GeneralHi! Pin
xeqtr_hyd17-Oct-07 10:32
xeqtr_hyd17-Oct-07 10:32 
QuestionWhat About Proxy Pin
james_wheeler_pe11-Oct-07 6:53
james_wheeler_pe11-Oct-07 6:53 
Generaldemo Pin
vidhya1021-Sep-07 1:21
vidhya1021-Sep-07 1:21 
GeneralRe: demo Pin
AmitDey21-Sep-07 3:40
AmitDey21-Sep-07 3:40 
GeneralUnwillful client disconnection Pin
Cybrosys24-Aug-07 2:21
Cybrosys24-Aug-07 2:21 
GeneralRe: Unwillful client disconnection Pin
AmitDey24-Aug-07 3:21
AmitDey24-Aug-07 3:21 
QuestionCreating User Groups Pin
Anand_na13-Aug-07 0:35
Anand_na13-Aug-07 0:35 
AnswerRe: Creating User Groups Pin
AmitDey13-Aug-07 3:50
AmitDey13-Aug-07 3:50 
QuestionRe: Creating User Groups Pin
Anand_na13-Aug-07 18:41
Anand_na13-Aug-07 18:41 
QuestionHow it works in LAN??? Pin
DeksInf12314-May-07 11:28
DeksInf12314-May-07 11:28 
AnswerRe: How it works in LAN??? Pin
AmitDey14-May-07 17:57
AmitDey14-May-07 17:57 
GeneralRe: How it works in LAN??? Pin
Vaskar Paul27-Jun-07 1:00
Vaskar Paul27-Jun-07 1:00 
Questionunrecogonize database Pin
fyclinic1-May-07 21:00
fyclinic1-May-07 21:00 
AnswerRe: unrecogonize database Pin
AmitDey1-May-07 23:03
AmitDey1-May-07 23:03 
GeneralRe: unrecogonize database Pin
fyclinic2-May-07 21:49
fyclinic2-May-07 21:49 
GeneralRe: unrecogonize database Pin
fyclinic5-May-07 20:30
fyclinic5-May-07 20:30 
GeneralRe: unrecogonize database Pin
AmitDey10-May-07 6:36
AmitDey10-May-07 6:36 
GeneralRe: unrecogonize database Pin
fyclinic14-May-07 1:28
fyclinic14-May-07 1:28 
Generaladd more data Pin
maxrpgg18-Apr-07 6:28
maxrpgg18-Apr-07 6:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.