Click here to Skip to main content
Click here to Skip to main content

A Simple Multi-Threaded Server Client Instant Messenger Application

, 4 Jun 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
A Simple Multi-Threaded Server Client Instant Messenger Application that uses TCP Listener and TCP Client. Allows Personal message and Conference communication between Clients and with the Server
Sample Image - maximum width is 600 pixels

The Library Project

I created a ChatLibrary that will contain the valid commands and a Message that will contain the parsing.

public enum Command
{
   Login = 0,
   PersonalMessage = 1,    
   ClientList = 2,        
   Conference = 3,
   Logout = 4        
};

public class Message
{
string strSender;
string strReceiver;
Command cmdMessageCommand;
string strMessageDetail;
public Message ()
{
}
public Message (byte [] rawMessage)
{
  string strRawStringMessage = System.Text.Encoding.ASCII.GetString (rawMessage);   
  string [] strRawStringMessageArray = strRawStringMessage.Split(new char []{'|'});
  this.strSender = strRawStringMessageArray[1];
  this.strReceiver = strRawStringMessageArray[2];
  this.cmdMessageCommand = (Command) Convert.ToInt32(strRawStringMessageArray[3]);
  this.MessageDetail = strRawStringMessageArray[4];
}
...

public byte [] GetRawMessage ()
{
   System.Text.StringBuilder sbMessage = new System.Text.StringBuilder ("John");
   sbMessage.Append("|");
   sbMessage.Append(strSender);
   sbMessage.Append("|");
   sbMessage.Append(strReceiver);
   sbMessage.Append("|");
   sbMessage.Append((int)cmdMessageCommand);
   sbMessage.Append("|");
   sbMessage.Append(strMessageDetail);
   sbMessage.Append("|");
   return System.Text.Encoding.ASCII.GetBytes(sbMessage.ToString());
}
...

The Server Project

I created a SocketServer that calls the TCPListener.Start() method:

IPEndPoint endPoint = new IPEndPoint (ipaAddress, iPort);
listener = new TcpListener (endPoint);
listener.Start();

Upon calling Listen, a new thread will be created that will listen for incoming clients:

thrListenForClients = new Thread(new ThreadStart(ListenForClients));
thrListenForClients.Start();

The ListenForClients method will wait for connections and will assign the incoming socket to a new Client instance:

Client acceptClient = new Client();
acceptClient.Socket = listener.AcceptTcpClient();
listenForMessageDelegate = new ListenForMessageDelegate (ListenForMessages);
listenForMessageDelegate.BeginInvoke
    (acceptClient, new AsyncCallback(ListenForMessagesCallback), "Completed");

The Client, by the way is a class that contains a TCPClient, so we can keep track of our connections:

public class Client {
   string strName;
   TcpClient tcpClient;
   public Client()
   {
   }
   public string Name 
   {
    get{return strName;}
    set{ this.strName = value;}            
   }
   public TcpClient Socket
   {
    get{return tcpClient;}
    set{ this.tcpClient = value;}
   }
   public void SendMessage (Message sendMessage)
   {
    NetworkStream stream = tcpClient.GetStream();
    stream.Write(sendMessage.GetRawMessage() , 0, sendMessage.GetRawMessage().Length);            
   }
}

Our server is now ready to listen for incoming messages. To do this, we pass the client socket that we received, then make a loop. We use a NetworkStream to read the message:

NetworkStream stream = client.Socket.GetStream();
byte [] bytAcceptMessage = new byte [1024];
stream.Read(bytAcceptMessage, 0, bytAcceptMessage.Length);
Message message = new ChatLibrary.Message(bytAcceptMessage);

Once we receive the message, we can do anything that we want:

txtStatus.Text += "\r\n" + strDisplayMessageType + 
    strWriteText.TrimStart(new char[]{'\r','\n'});

My SocketServer makes use of a few events that make coding a little easier:

public event ClientConnectedEventHandler ClientConnected;
public event ClientDisconnectingEventHandler ClientDisconnecting;
public event MessageReceivedEventHandler MessageReceived;

In my ServerForm code, what I did was I kept a copy of each connected Client in a ClientCollection that inherits from System.Collections.CollectionBase. With this, I can iterate through the Clients.

The Client Project

The Client does basically the same thing. I created a ClientSocket that will create a TCPListener and call Connect():

IPEndPoint serverEndpoint = new IPEndPoint (ipaAddress , iPort);
tcpClient = new TcpClient ();
tcpClient.Connect(serverEndpoint);
thrListenForMessages = new Thread (new ThreadStart(ListenForMessages));
thrListenForMessages.Start();

What ListenForMessages will do is loop with NetworkStream.Read():

stream = tcpClient.GetStream();
byte [] bytRawMessage = new byte [1024];
stream.Read(bytRawMessage, 0, bytRawMessage.Length);
ChatMessage receivedMessage = new ChatLibrary.Message (bytRawMessage);

Then we do the same process, create a Message using the received bytes.

Again, my goal is to create a YM/MSN - looking Instant Messenger, so I made two UI forms. The MessengerForm and the ClientWindow. The MessengerForm is the class that instantiates the ClientSocket and receives the messages. Upon receiving a message, it calls the MessengerWindow that should display the text.

Note that I didn't do a regular instantiation. I called Invoke to be able to make my controls thread safe:

this.Invoke(createNewClientDelegate, new object []{receivedMessage});

History

  • 4th June 2006: Initial version

License

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

Share

About the Author

John Conrad
Web Developer
Philippines Philippines
John lives in the Philippines with his family, working as a programmer. He used to program VB6 but is now... ummm... trying to learn C# .Net.

Comments and Discussions

 
GeneralCross threading issue in Visual Studio 2013... PinmemberArslan Tariq22-May-14 10:20 
Generalthis code can not send bytes>1024 Pinmemberdaodetianzun19-Sep-08 5:09 
GeneralGreat but there are some errors to modify PinmemberSugathe0427-Aug-08 19:43 
GeneralHelp Please: If I kick a client, or client click disconnect, the server raises a error of "Server has stopped working" PinmemberJameYoon2-Jul-08 18:35 
GeneralPlease Help :) If I stop the Server(even if there is no client connected), it arises an error. [modified] PinmemberJameYoon1-Jul-08 19:18 
QuestionNot sure how to use!!! PinmemberLecram21-Jun-08 21:34 
GeneralCross-thread operation not valid: Control 'txtStatus' accessed from a thread other than the thread it was created on. PinmemberShawn12814-Jun-08 23:42 
AnswerRe: Cross-thread operation not valid: Control 'txtStatus' accessed from a thread other than the thread it was created on. PinmemberJason Barry25-Jun-08 3:57 
You can't access an object that wasn't created on the thread you're calling from. So there is a work around using delegates. The code below is how you would accomplish this in your case:
 
private delegate void AddStatusTextDelegate(string text);
 
private void AddStatusText(string text)
{
    if (this.txtStatus.InvokeRequired)
    {
        // This is a worker thread so delegate the task.
        this.txtStatus.Invoke(new AddStatusTextDelegate(this.AddStatusText), text);
    }
    else
    {
        // This is the UI thread so perform the task.
        this.txtStatus.Text += text;
    }
}

GeneralRe: Cross-thread operation not valid: Control 'txtStatus' accessed from a thread other than the thread it was created on. PinmemberMember 87892936-Apr-12 11:16 
QuestionClient IP-Address problem PinmemberHusti5-Apr-08 10:03 
GeneralSystem.ObjectDisposedException after disconnect PinmemberGaara [BTK]15-Aug-07 15:22 
GeneralRe: System.ObjectDisposedException after disconnect PinmemberAntbu1325-Oct-07 21:41 
GeneralRe: System.ObjectDisposedException after disconnect PinmemberEagleTwo20-May-09 11:43 
Generalproblem in running this application [modified] Pinmembervrani12-Jul-07 20:38 
GeneralMulti-threading error fix Pinmemberstormist10-Jun-07 14:43 
Generaltextbox Pinmemberdark_magician_65-May-07 5:50 
Questionnot working on lan plz help me PinmemberMember #37941123-Mar-07 1:26 
Questionit is working in LAN but what do i need to do for WAN ? Pinmemberevalenzuela2-Feb-07 12:57 
GeneralError PinmemberChristian Siebmanns7-Oct-06 6:04 
GeneralRe: Error Pinmemberbubbler_below9-Oct-06 18:09 
GeneralRe: Error Pinmemberbubbler_below10-Oct-06 23:25 
GeneralRe: Error PinmemberChristian Siebmanns21-Oct-06 6:24 
AnswerRe: Error Pinmemberduffer_0113-Apr-07 11:30 
AnswerRe: Error Pinmember@Jim13-Aug-07 11:06 
GeneralRe: Error Pinmembershnewaz20-Apr-08 7:55 
GeneralRe: Error PinmembermarcoTDI13-May-08 22:47 
Generalhi Pinmemberibless17-Aug-06 13:32 
GeneralRe: hi PinmemberChristian Siebmanns21-Oct-06 6:07 
Generalvery nice work PinmemberDarchangel3-Aug-06 5:00 
GeneralRe: very nice work Pinmembershnewaz20-Apr-08 7:57 
GeneralRichtext Formatting PinmemberYadav Pramod26-Jul-06 22:54 
GeneralRe: Richtext Formatting Pinmembermassivegas29-Jul-06 22:12 
GeneralGood application Pinmemberdeepak_int18-Jun-06 20:28 
GeneralRe: Good application Pinmembermassivegas19-Jun-06 21:25 
GeneralIt works Pinmemberrduan12-Jun-06 10:04 
GeneralYou got my 5 for... PinmemberJun Du5-Jun-06 5:18 
Generalhi Pinmembernina0003-Mar-08 7:04 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 5 Jun 2006
Article Copyright 2006 by John Conrad
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid