Click here to Skip to main content
Licence CPOL
First Posted 18 Oct 2006
Views 142,044
Downloads 13,382
Bookmarked 115 times

Multithreaded Chat Server

By | 31 Jan 2007 | Article
This is a simple multithreaded chat server, intended for people to learn Socket programming and Threads in C#.

Sample Image - Chat.jpg

Introduction

I started writing this application to learn Socket programming, Threads, and UI controls in C#. But in the process, I learned more than that. We would go step by step and will try to cover all important aspects of this application. But before we begin, I'd like to set some expectations about the application. This application demonstrates how multiple clients can connect to a single server and communicate to the server. However, at this point, clients cannot communicate with each other. That would be the next step for this application.

Using the code

What do you need to get started with a multithreaded chat application? Threads and Sockets.

Following is how the application starts and how it works:

  1. As soon as the application is started, the main thread is spawned by the system.
  2. The main thread then spawns a thread which keeps listening on a given port.
  3. As soon as there is any connection request from a client, a connection is established. After the connection gets established, another thread is spawned to open a dialog box for chatting with clients.
  4. For every connection to a client, a new thread is spawned. Hence, if there are three clients connected to the server, then the total active threads will be five, one main thread, one thread for listening, and one each for chatting with the connected clients.

Now, let's look at what each thread, that corresponds to a client connect, does:

  1. Calls the asynchronous BeginReceive method. A callback method is passed a parameter. This callback method is called when any data is received on that socket.
  2. When data is received on a socket, the data is read and displayed on the rich text box of the chat dialog. However, if a SocketException is raised, then the connection is closed, as this means that the client has asked to close the connection.
  3. When the Send button is clicked, data is sent to client.

Huh! Looks pretty simple. Now, let's look at some concepts in C# that are required to understand the implementation.

1. How does asynchronous receive work?

.NET framework's Socket class provides a BeginReceive method to receive data asynchronously, i.e., in a non-blocking manner. The BeginReceive method has the following signature:

public IAsyncResult BeginReceive( byte[] buffer, int offset, int size, 
   SocketFlags socketFlags, AsyncCallback callback, object state );

The way the BeginReceive function works is that, you pass the function a buffer and a callback function (delegate) which will be called whenever data arrives. The callback method is called by the system when data is received on the given socket. This method is called using a separate thread (internally spawned by the system). Hence this operation is asynchronous and non-blocking.

Now, where exactly will be the received data? It will be in the buffer that was passed in the BeginReceive method. But before you read the data, you should know the number of bytes that has been received. This is achieved by calling the EndReceive method of the Socket class.

The BeginReceive call is completed only after the EndReceive method of the Socket. The following code will clear what has been explained in the above paragraphs:

BeginReceive call is made:

// Create the state object. 
StateObject state = new StateObject(); 
state.workSocket = connectedClient.Client; 

//Call Asynchronous Receive Function 
connectedClient.Client.BeginReceive(state.buffer, 0, 
  StateObject.BufferSize, 0,new AsyncCallback(OnReceive), state);

Callback function when data is received on the Socket:

public void OnReceive(IAsyncResult ar) 
{ 
  String content = String.Empty; 
  // Retrieve the state object and the handler socket  
  // from the asynchronous state object. 

  StateObject state = (StateObject)ar.AsyncState; 
  Socket handler = state.workSocket; 
  int bytesRead; 
  if (handler.Connected) 
  { 
    // Read data from the client socket. 

    try  
    { 
      bytesRead = handler.EndReceive(ar); 
      if (bytesRead > 0) 
      { 
        // There might be more data, so store the data received so far.
        state.sb.Remove(0, state.sb.Length); 
        state.sb.Append(Encoding.ASCII.GetString( 
        state.buffer, 0, bytesRead)); 
        
        // Display Text in Rich Text Box  
        content = state.sb.ToString(); 
        SetText(content); 
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 
                             0,new AsyncCallback(OnReceive), state); 
      } 
    } 
    catch (SocketException socketException) 
    { 
      //WSAECONNRESET, the other side closed impolitely 
      if (socketException.ErrorCode == 10054 || 
         ((socketException.ErrorCode != 10004) && 
         (socketException.ErrorCode != 10053))) 
      { 
         // Complete the disconnect request.
         String remoteIP = 
           ((IPEndPoint)handler.RemoteEndPoint).Address.ToString(); 
         String remotePort = 
           ((IPEndPoint)handler.RemoteEndPoint).Port.ToString(); 
         this.owner.DisconnectClient(remoteIP, remotePort); 
         handler.Close(); 
         handler = null; 
       } 
     } 
    // Eat up exception....Hmmmm I'm loving eat!!!  
    catch (Exception exception) 
    { 
      MessageBox.Show(exception.Message + "\n" + exception.StackTrace); 
    } 
  } 
}

2. How can you access a User Interface control (e.g., RichText Box) from a thread which is not an owner of that UI control?

Answer is, use Delegates.

If you look at the application, The rich text box that displays the chat message is created by the thread that creates the chat dialog box. Now, the chat data in the rich text box is updated by a thread that calls the callback function, OnReceive. This is a system spawned thread!

In order to access it, create a delegate as:

public delegate void SetTextCallback(string s);

Now, create a function to update the rich text box as:

private void SetText(string text) 
{ 
// InvokeRequired required compares the thread ID of the 
// calling thread to the thread ID of the creating thread. 
// If these threads are different, it returns true. 

  if (this.rtbChat.InvokeRequired) 
  { 
    SetTextCallback d = new SetTextCallback(SetText); 
    this.Invoke(d, new object[] { text }); 
  } 
  else 
  { 
    this.rtbChat.SelectionColor = Color.Blue; 
    this.rtbChat.SelectedText = "\nFriend: "+text; 
   } 
}

History

  • Updated on 12/13/2006 - Formatted article, and added a few details.
  • Updated on 01/31/2007 - Updated the sample client code and added validation to port the text box in server code.

License

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

About the Author

Sidzone

Web Developer

United States United States

Member

Sid works in one of the top IT consulting company, in Datawarehousing projects.
MS Technologies has always excited him. He codes in C# for fun.
 
Apart from keen interest in .NET, Sid loves computer games(NFS being his favorite), playing cricket and has passion for photography.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
AnswerRe: Does it work with the internet ? PinmemberSidzone9:31 20 Nov '07  
GeneralRe: Does it work with the internet ? PinmemberMohandas P G0:10 2 Sep '11  
GeneralMDI and Show - How can I use it in this source Pinmembermaithang_longthanh16:18 21 Jun '07  
GeneralNice article Pinmemberxs2mini3:17 11 Apr '07  
GeneralThank you Pinmemberduc_clo18:01 8 Apr '07  
GeneralNice and simple - thanks! PinmemberPatrick Sears9:05 31 Jan '07  
GeneralThank you for the code PinmemberSin Jeong-hun5:51 18 Jan '07  
I finally found this simple example where I can get started. I just tested the demo executables and haven't inspected the code yet. I just don't know why the rating is so poor. I'll vote for "Excellent" right after writing this. Anyways, I would like to use this server/client code for my program's communication part.
 
There's an error. The default port number is empty so I check Start/Stop without filling that box, it crashes. Furthur more, if the port number is not 6768 the client doesn't start. Yes if I look into the soure code of the client, then I know 6768 is needed but for a quick demo, most people tend to start just the program first.
 
And the client interface is confusing. I thought the log dialog was popped up at the client. I typed there again and again but nothing happened. So, could you update the sample cleint program so that it uses simple GUI or, just print "Type message to send to the server" at the console right after "Connected..." is printed?
GeneralRe: Thank you for the code PinmemberSidzone9:12 31 Jan '07  
GeneralPrepare your code PinmemberSceptic Mole2:57 5 Nov '06  
GeneralRe: Prepare your code PinmemberSidzone23:36 26 Feb '07  
Generalclient server Pinmemberhduani5:45 27 Oct '06  
GeneralRe: client server PinmemberSidzone20:09 31 Oct '06  
GeneralRe: client server Pinmemberchal_adiera20:59 31 Oct '06  
GeneralRe: client server Pinmemberchal_adiera21:18 31 Oct '06  
GeneralRe: client server PinmemberSidzone2:35 1 Nov '06  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 31 Jan 2007
Article Copyright 2006 by Sidzone
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid