Best / Easiest Way to Approach a Chat Client?

Posted on 2009-05-11
Last Modified: 2012-05-06
I'm learning to program, and I want to try making a simple chat client.  It should connect to a server running a different executable.  What would be the best way to learn how to do this?  I was thinking have clients messages in a txt file and give the contents of the file every time they ask for it.  But I think that might be laggy.  Another way would be to stay connected to the server and receive new messages.  Here's some code I found on the internet:


      Dim tcpClient As New System.Net.Sockets.TcpClient()

      tcpClient.Connect("", 8000)

      Dim networkStream As NetworkStream = tcpClient.GetStream()

      If networkStream.CanWrite And networkStream.CanRead Then

        ' Do a simple write. 

        Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("CLIENT: This is my message")

        networkStream.Write(sendBytes, 0, sendBytes.Length)

        ' Read the NetworkStream into a byte buffer.

        Dim bytes(tcpClient.ReceiveBufferSize) As Byte

        networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))

        ' Output the data received from the host to the console.

        Dim returndata As String = Encoding.ASCII.GetString(bytes)

        MessageBox.Show("CLIENT: The server returned: " + returndata)


        If Not networkStream.CanRead Then

          MessageBox.Show("CLIENT: cannot not write data to this stream")



          If Not networkStream.CanWrite Then

            MessageBox.Show("CLIENT: cannot read data from this stream")


          End If

        End If

      End If

    Catch exception As SocketException

      MessageBox.Show("CLIENT: Could not connect to server")

    End Try


    Const portNumber As Integer = 8000

    Const server As String = ""

    Dim tcpListener As New TcpListener(System.Net.IPAddress.Parse(server), portNumber)


    MessageBox.Show("SERVER: waiting for con")


      'Accept the pending client connection and return a TcpClient initialized for communication. 

      Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()

      MessageBox.Show("SERVER: Connection accepted.")

      ' Get the stream

      Dim networkStream As NetworkStream = tcpClient.GetStream()

      ' Read the stream into a byte array

      Dim bytes(tcpClient.ReceiveBufferSize) As Byte

      networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))

      ' Return the data received from the client to the console.

      Dim clientdata As String = Encoding.ASCII.GetString(bytes)

      MessageBox.Show("SERVER: Client sent: " + clientdata)

      Dim responseString As String = "I'm the server. You're connected"

      Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)

      networkStream.Write(sendBytes, 0, sendBytes.Length)

      MessageBox.Show("SERVER: Message Sent: " + responseString)

      'Any communication with the remote client using the TcpClient can go here.

      'Close TcpListener and TcpClient.



    Catch ex As Exception


    End Try

Open in new window

Question by:freebullets
1 Comment
LVL 31

Accepted Solution

Frosty555 earned 50 total points
ID: 24361173
The best way to approach this is to do it using TCP.  Use the TCPClient and TCPListener classes like the code snippet you provided above uses. Don't use text files / other shared resources. You can easily communicate between your clients using TCP, whether they are on the LAN, or across the internet.

#1 first thing you must do is UNDERSTAND how TCP communication works. It's not totally trivial. Until you know what the communication model looks like, you will have a hard time understanding how .NET implemented it.

Read this first:

Now you can dive into the .NET side of things. Before .NET, TCP communication was done using Winsock, which is complicated in comparison. The .NET platform has simplified the whole winsock thing quite a lot. One program uses the TCPClient class, and connects to the server. The other program uses TCPListener, and waits for an incoming client. After the handshaking is done (which is done through a couple callback routines and events, provided you want to do it asynchronously), you can send data on one end, and receieve it on the other, and vice versa.

The communication is done by having client and server read and write to a NetworkStream object, which is just like any other stream object in .NET. This means there is no individual "messages" being sent. Just a single long stream of data. This means several individual "writes" to the network buffer may not result in the same number of "reads" on the other side. Nor will it necessarily arrive on the other side in once piece, or at the same time. It's just one long stream. For that reason it would be in your best interest to devise a data "protocol" of your own. Maybe a special pattern of characters to signify the end of each chat mesage.

Simple Example:

The MSDN actually has a pretty decent example too:
TCPClient -
TCPListener -

Keep in mind that TCP connections are done using an IP address, and a Port. If the server is behind a firewall, you have to forward the port that the server is listening on to the server's inner address. That's just the way internet communication works. Real chat systems get around this by having a central "chat" server with all the appropriate settings and port forwarding already setup. All the clients connect to that, and talk to each other through the server. The server plays the roll of handing messages from one client to the other, and is never actually a member of any particular chat session. That's a more complicated example, and to do that you need to write a server capable of hosting several clients. That is called a "multithreaded tcp server". To do that you need an understanding of how threading works in .NET.

A good discussion is here:

But for now, considering this is a learning exercise for you, I suggest you just work on client/server communication first. Work on the fancy stuff later.

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now