Solved

Best / Easiest Way to Approach a Chat Client?

Posted on 2009-05-11
1
185 Views
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:
Client:
 
    Try
      Dim tcpClient As New System.Net.Sockets.TcpClient()
      tcpClient.Connect("127.0.0.1", 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)
      Else
        If Not networkStream.CanRead Then
          MessageBox.Show("CLIENT: cannot not write data to this stream")
          tcpClient.Close()
        Else
          If Not networkStream.CanWrite Then
            MessageBox.Show("CLIENT: cannot read data from this stream")
            tcpClient.Close()
          End If
        End If
      End If
    Catch exception As SocketException
      MessageBox.Show("CLIENT: Could not connect to server")
    End Try
 
Server:
 
    Const portNumber As Integer = 8000
    Const server As String = "127.0.0.1"
    Dim tcpListener As New TcpListener(System.Net.IPAddress.Parse(server), portNumber)
    tcpListener.Start()
    MessageBox.Show("SERVER: waiting for con")
    Try
      '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.
      tcpClient.Close()
      tcpListener.Stop()
    Catch ex As Exception
      MessageBox.Show(ex.ToString)
    End Try

Open in new window

0
Comment
Question by:freebullets
1 Comment
 
LVL 31

Accepted Solution

by:
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:
http://www.w3schools.com/tcpip/tcpip_intro.asp

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: http://www.eggheadcafe.com/articles/20020323.asp

The MSDN actually has a pretty decent example too:
TCPClient - http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx
TCPListener - http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx



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:
http://www.codeproject.com/KB/IP/dotnettcp.aspx

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.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
.net and XML report from SCCM 5 25
Regex validation 2 25
Formula problem with Excel attachment 6 27
Disable Security Alert  popup in Winforms  embedded webbrowser. 1 30
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
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…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

778 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