Learn .NET network programming by writing your own chat application, and in the process, create a slick client-server application that supports simultaneous conversations with multiple clients.

by Wie-Meng Lee

May 11, 2005

Page 3 of 3

Building the Client
Now that the server is built, it is time to build the client. Using Visual Studio 2005, I create a new Windows application (name it WinClient) and populate the default form with the controls shown in Table 1 (see the resulting form in Figure 2).

Table 1. Client Controls

Control(Name)

Property

Value

Label

Text

Nick

TextBox

Name

txtNick

TextBox

Name

txtMessageHistory

MultiLine

True

ReadOnly

True

TextBox

Name

txtMessage

Button

Name

btnSignIn

Text

Sign In

Button

Name

btnSend

Text

Send

The client application logic is very similar to the server, albeit more straightforward. Double-click on the form to switch to the edit window, and import the following namespace:

Figure 2. Adding Controls: Populate the Windows Form with the various controls from Table 1.

When the user signs in, the client first connects to the server and sends the nickname of the user using the SendMessage() subroutine (defined shortly). Then it should begin reading data from the server asynchronously and change the name of the Sign In button to "Sign Out." When the user signs out from the chat application, you invoke the Disconnect() subroutine (defined shortly).

The ReceiveMessage() subroutine asynchronously reads data sent from the server in a separate thread. When the data is received, it will display the data in the txtMessageHistory control. As Windows controls are not thread-safe, you need to use a delegate, delUpdateHistory(), to update the controls:

Testing the Application
To test the applications, first run the server by pressing F5 in Visual Studio 2005. You want to launch multiple copies of the client to test the multi-user capabilities of the server. To do this, compile the client-side code files provided with this article into an .exe file. Run multiple copies of Winclient.exe and sign in and chat at the same time.

In this article, I've shown how the TcpClient class allows you to perform asynchronous communication between two computers. While the chat application developed in this article is simple, it is a foundation on which to build more complicated chat applications. In my next article I'll do exactly that, adding FTP, private chats, and more to this simple chat application.

Wei-Meng Lee is a Microsoft .NET MVP and co-founder of Active Developer, a training company specializing in .NET and wireless technologies. He is a frequent speaker and author of numerous books on .NET, XML, and wireless technologies.