Solved

Best / Easiest Way to Approach a Chat Client?

Posted on 2009-05-11
1
190 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

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

Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
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…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
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…

730 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