Solved

Best / Easiest Way to Approach a Chat Client?

Posted on 2009-05-11
1
179 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
Comment Utility
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
vb6 connector to mongodb 2 25
Convert string to date 3 39
Library to convert HTML to PDF. 8 44
Problem to go to Web page 2 46
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
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…
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…

771 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

10 Experts available now in Live!

Get 1:1 Help Now