Click here to Skip to main content
11,576,692 members (59,102 online)
Click here to Skip to main content

A TCP/IP Chat Program

, 20 Aug 2009 CPOL 142.7K 33.7K 74
Rate this:
Please Sign up or sign in to vote.
A TCP/IP chat program coded in Microsoft Visual Basic .NET.

Introduction

For a while now, I have been looking for a solution to a chat program developed in VB.NET, but didn't find much, so I decided to try my own. The purpose of this article is to explain how to use TCP/IP Sockets and the My.Settings class included in .NET framework 2.0 and later. The good thing about this application is, the server and the client are not two separate applications. This form acts as both the Server and the Client.

Before You Start

Instead of creating my own file transfer functionality, I stumbled upon the UnoLibs.Net.dll. The beauty of this class is that all the work is done for you. Later in the article, I will explain how to put this code into practice.

To obtain a copy of this class, click here.

The Application

Using the Application (Rapid Chat)

  • To add a new IP address to the address box, double click your display picture.
  • Right click the "Send" button for more options.
  • Make sure the selected client is available by clicking the Connect button.

1. Sending Messages Using TCP/IP

First off, we need to make some declarations:

Imports System.Net.Sockets
Imports System.Threading 

Dim Listener As New TcpListener(65535)
Dim Client As New TcpClient
Dim Message As String = ""

You can use any socket you want. I usually choose one of the last few sockets just to be sure no other application is using them. Anything up to and including port 65535 is suitable for the job.

Now we need to start the listening process. This opens the specified socket to receive any packets of data sent to it. In the load event of the form, start the listener.

Dim ListenerThread As New Thread(New ThreadStart(AddressOf Listening))
ListenerThread.Start()

Private Sub Listening()
    Listener.Start()
End Sub

The listener would be useless without a timer. We need the timer to constantly update the listener to receive data.

Private Sub Timer1_Tick(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Timer1.Tick
    If Listener.Pending = True Then
        Message = ""
    Client = Listener.AcceptTcpClient()

    Dim Reader As New StreamReader(Client.GetStream())
    While Reader.Peek > -1
        Message = Message + Convert.ToChar(Reader.Read()).ToString
    End While
    RichTextBox1.ForeColor = Color.Black
    RichTextBox1.Text += Message + vbCrLf
    'Here you can enter anything you would like 
    'to happen when a message is received,
    'For instance; Play a sound, Show a message Box, A Balloon Tip etc.
End Sub

Now to send a message to a particular client:

Private Sub btnSend_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnSend.Click
    If txtName.Text = "" Or cmbAddress.Text = "" Then
        'Check to make sure that the user has entered 
        'a display name, and a client IP Address
        'If Not, Show a Message Box
        MessageBox.Show("All Fields must be Filled", _
                        "Error Sending Message", _
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
        Try
            Client = New TcpClient(cmbAddress.Text, 65535)

            'Declare the Client as an IP Address. 
            'Must be in the Correct form. eg. 000.0.0.0
            Dim Writer As New StreamWriter(Client.GetStream())
            Writer.Write(txtName.Text & " Says:  " & txtmessage.Text)
            Writer.Flush()

            'Write the Message in the stream

            RichTextBox1.Text += (txtName.Text & " Says:  " & txtmessage.Text) + vbCrLf
            txtmessage.Text = ""
        Catch ex As Exception
            Console.WriteLine(ex)
            Dim Errorresult As String = ex.Message
            MessageBox.Show(Errorresult & vbCrLf & vbCrLf & _
                            "Please Review Client Address", _
                            "Error Sending Message", _
                            MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End If
End Sub

And that's it for sending messages.

Now to set up file transferring using UnoLibs.Net.dll.

2. File Transfer Using the UnoLibs.Net.dll Class

The thing I love about this class is it is so simple to use. It's quick, easy, and best of all, it works!

Start off by referencing it in your project.

Imports UNOLibs.Net.ClientClass

Declare the client and the server.

Dim clnt As New UNOLibs.Net.ClientClass
Dim WithEvents server As UNOLibs.Net.ServerClass

Now to send some files to the client:

Private Sub SendFileToolStripMenuItem_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles SendFileToolStripMenuItem.Click
    OpenFileDialog1.ShowDialog()

    If DialogResult.OK Then
        RichTextBox1.Text += (txtName.Text & " Is Sending You a File...") + vbCrLf
        clnt.SendFiles(cmbAddress.Text, 65533, OpenFileDialog1.FileNames)
    Else
        Exit Sub
    End If

End Sub

Using the My.Settings Class in VB.NET

I decided to put this section in my article because I know there is some confusion when it comes to saving user and/or application settings in VB.NET. The great thing about the My.Settings class is that very little code is needed to save a huge variety of settings. The My.Settings class allows you to save such things as:

  • Strings (most common)
  • Font
  • Form size, colour, state etc.
  • Checkstate
  • Integers
  • And many more

To create a setting, in your project, go to Project > (Your Project Name) Properties, and choose the Settings tab. Enter a name, Type (Usually String), Scope (User or Application), and a value for the setting.

To load a setting at startup, for a string setting, it might look something like this:

TextBox1.Text = My.Settings.RandomString

To change the value of a setting during runtime, it is virtually the same.

My.Settings.RandomString = RichTextBox1.Text

Your application will automatically save user-scoped settings on exit. To enable or disable this setting, do the following:

My.Application.SaveMySettingsOnExit = True
'Or
My.Application.SaveMySettingsOnExit = False

It's as simple as that. No need to load XML files and re-write them.

License

This code can be used freely without limitations. Check the code in the project file for more information on licensing.

History

  • Aug 13, 2009 -- Original Post Date
  • Aug 20, 2009
    • Minor bug Fixes
    • Some features added
    • Missing source files added

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Andrew Courtice
Australia Australia
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionHow to chat between two PCs not in the same LAN Pin
khairy30-Dec-14 1:01
memberkhairy30-Dec-14 1:01 
SuggestionRe: How to chat between two PCs not in the same LAN Pin
Member 1138179620-Jan-15 17:38
memberMember 1138179620-Jan-15 17:38 
QuestionGreat Pin
Juan Diego Valencia26-Sep-14 5:45
memberJuan Diego Valencia26-Sep-14 5:45 
QuestionCHat Program Pin
Member 1104183427-Aug-14 21:07
memberMember 1104183427-Aug-14 21:07 
QuestionBug for sending files Pin
jonald zeine4-Jun-14 0:22
memberjonald zeine4-Jun-14 0:22 
QuestionCan I use UnoLibs.Net.dll forever? Pin
dinhnq20-Jun-13 15:33
memberdinhnq20-Jun-13 15:33 
GeneralThnks Pin
rfatcakr19-Jun-13 2:36
memberrfatcakr19-Jun-13 2:36 
QuestionDatabase for Rapid Project Pin
Irahsyairah16-May-13 14:46
memberIrahsyairah16-May-13 14:46 
Questioncan you help me? Pin
mouse7114-Jan-13 18:07
membermouse7114-Jan-13 18:07 
AnswerRe: can you help me? Pin
Juan Diego Valencia26-Sep-14 5:44
memberJuan Diego Valencia26-Sep-14 5:44 
Questionwho wan to help me about this software? Pin
mouse71122-Dec-12 18:36
membermouse71122-Dec-12 18:36 
QuestionWell That's Awesome Pin
Apoorva Gora18-Dec-12 0:45
memberApoorva Gora18-Dec-12 0:45 
QuestionHi Andrew Pin
shaha412-Apr-12 23:18
membershaha412-Apr-12 23:18 
Generalhow to I see other online users Pin
vmaxp21-Apr-11 3:04
membervmaxp21-Apr-11 3:04 
GeneralMy vote of 4 Pin
bagoes4all28-Dec-10 5:35
memberbagoes4all28-Dec-10 5:35 
GeneralMy vote of 5 Pin
iamgowda16-Dec-10 23:01
memberiamgowda16-Dec-10 23:01 
QuestionMultithread Server Pin
M_Amin12-Nov-10 4:19
memberM_Amin12-Nov-10 4:19 
GeneralMy vote of 5 Pin
andersonguilherm11-Jul-10 21:11
memberandersonguilherm11-Jul-10 21:11 
GeneralMy vote of 1 Pin
Rio_Grande6-May-10 5:40
memberRio_Grande6-May-10 5:40 
Rant[My vote of 2] Incomplete coding Pin
JSH2313-Apr-10 14:13
memberJSH2313-Apr-10 14:13 
GeneralMy vote of 1 Pin
arkamukherjee21-Feb-10 20:18
memberarkamukherjee21-Feb-10 20:18 
Generalfinding dll Pin
joesamraj7-Jan-10 21:03
memberjoesamraj7-Jan-10 21:03 
Generalso good Pin
Abdinoo19-Sep-09 1:57
memberAbdinoo19-Sep-09 1:57 
GeneralMy Vote of 2 Pin
_Khallaf18-Sep-09 9:14
member_Khallaf18-Sep-09 9:14 
GeneralRe: My Vote of 2 Pin
slimtugo6-Sep-10 7:15
memberslimtugo6-Sep-10 7:15 
GeneralMy vote of 2 Pin
_Khallaf18-Sep-09 9:07
member_Khallaf18-Sep-09 9:07 
you need to learn more about TcpClient and TcpListener before publishing an article about sample programs done with them. Play more with the two classes and explore properties, functions and methods!
General[My vote of 2] ok article Pin
Donsw12-Sep-09 16:31
memberDonsw12-Sep-09 16:31 
GeneralHi Pin
Sin Sareth9-Sep-09 23:54
memberSin Sareth9-Sep-09 23:54 
GeneralMy vote of 1 Pin
BooGhost9-Sep-09 12:36
memberBooGhost9-Sep-09 12:36 
GeneralMy vote of 1 Pin
PKBoone18-Aug-09 5:20
memberPKBoone18-Aug-09 5:20 
Generalbug number 3 Pin
PKBoone18-Aug-09 5:18
memberPKBoone18-Aug-09 5:18 
GeneralBug number 2 Pin
PKBoone18-Aug-09 5:14
memberPKBoone18-Aug-09 5:14 
GeneralRe: Bug number 2 Pin
Andrew Courtice18-Aug-09 15:33
memberAndrew Courtice18-Aug-09 15:33 
GeneralMissing Message.png file in Source Pin
PKBoone18-Aug-09 5:08
memberPKBoone18-Aug-09 5:08 
GeneralMissing error correction Pin
PKBoone18-Aug-09 4:57
memberPKBoone18-Aug-09 4:57 
GeneralRe: Missing error correction Pin
Andrew Courtice18-Aug-09 13:09
memberAndrew Courtice18-Aug-09 13:09 
GeneralMissing assemblies Pin
PKBoone18-Aug-09 4:35
memberPKBoone18-Aug-09 4:35 
GeneralRe: Missing assemblies Pin
PKBoone18-Aug-09 4:42
memberPKBoone18-Aug-09 4:42 
GeneralRe: Missing assemblies Pin
joesamraj7-Jan-10 21:02
memberjoesamraj7-Jan-10 21:02 
GeneralLooking good! Pin
Ant210012-Aug-09 2:06
memberAnt210012-Aug-09 2:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150603.1 | Last Updated 20 Aug 2009
Article Copyright 2009 by Andrew Courtice
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid