Click here to Skip to main content
12,351,441 members (35,519 online)
Click here to Skip to main content
Add your own
alternative version


80 bookmarked

A TCP/IP Chat Program

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


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))

Private Sub Listening()
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)
            Client = New TcpClient(cmbAddress.Text, 65535)

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

            'Write the Message in the stream

            RichTextBox1.Text += (txtName.Text & " Says:  " & txtmessage.Text) + vbCrLf
            txtmessage.Text = ""
        Catch ex As Exception
            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

    If DialogResult.OK Then
        RichTextBox1.Text += (txtName.Text & " Is Sending You a File...") + vbCrLf
        clnt.SendFiles(cmbAddress.Text, 65533, OpenFileDialog1.FileNames)
        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
My.Application.SaveMySettingsOnExit = False

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


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


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


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


About the Author

Andrew Courtice
Australia Australia
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionNot a good program
Mike Jo25-Nov-15 21:38
memberMike Jo25-Nov-15 21:38 
This is not a good program:
1. You don't reuse the accepted client socket to send or receive message later
2. You don't reuse the client socket that had been created before. In your case, you create a new socket client whenever 'send' is clicked

I'm designing a peer-to-peer program using TCP socket like your idea but it doesn't run smoothly and I'm finding a solution for it.

QuestionLink broken to the UnoLibs dll
Member 90411913-Nov-15 2:43
memberMember 90411913-Nov-15 2:43 
This one works, though:

TCP/IP With VB.Net - version 2(more power-more ease)

Thanks for the code, hey...
QuestionError on Send some file
John Carlo Deveras11-Nov-15 15:50
memberJohn Carlo Deveras11-Nov-15 15:50 
"Error retriving port from server"
i got that error when sending some file... PLEASE HELP me.. thankss

... i put this code on the BUTTON

        If DialogResult.OK Then
            RichTextBox1.Text += (TextBox1.Text & " Is Sending You a File...") + vbCrLf
            clnt2.SendFiles(txtaddress.Text, 65533, OpenFileDialog1.FileNames) ' << this line is Highlighted when error occur
            Exit Sub
        End If

QuestionVisual studio 2013 - question about error
Member 120302933-Oct-15 5:27
memberMember 120302933-Oct-15 5:27 
I am using visual studio 2013 and i just downloaded this tcp/ip chat program and i wanted to connect to my computer but it doesn't show a IP with VS 2013, when i start the exe it works fine.

But when i do this with VS 2013, i receive the following error when i type in a new adress at the icon button next to client data: An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll

Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick

At this part:
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()

The rest of the code:
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
If frmSettings.chkSound.CheckState = CheckState.Unchecked Then
    NotifyIcon1.BalloonTipTitle = ("New Message")
    NotifyIcon1.BalloonTipText = Message
    NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info
    frmMessage.lblMessage.Text = Message
    lblStat.Text = ("Last Message Received At " & My.Computer.Clock.LocalTime)
    NotifyIcon1.BalloonTipTitle = ("New Message")
    NotifyIcon1.BalloonTipText = Message
    NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info
    frmMessage.lblMessage.Text = Message
    lblStat.Text = ("Last Message Received At " & My.Computer.Clock.LocalTime)
End If

I really would like to know what i should change there, because i would like to use it. I hope some one still would answer this question here.
QuestionHow to chat between two PCs not in the same LAN
khairy30-Dec-14 1:01
memberkhairy30-Dec-14 1:01 
Dear Sir:
thanks for your effort.
I hope to find answer for this question:
How to chat between two PCs not in the same LAN,
example my PC in home with other PC in work.
as you know, each PC will take local IP may like 192.168.1.x
how can i communicate between them.

Best regards
SuggestionRe: How to chat between two PCs not in the same LAN
Member 1138179620-Jan-15 17:38
memberMember 1138179620-Jan-15 17:38 
Just double-click the profile photo icon and then just enter a new ip, then open the drop down menu beside the connect button and just select the ip you had typed >> click connect >> enter your name >> chat!!!
Juan Diego Valencia26-Sep-14 5:45
memberJuan Diego Valencia26-Sep-14 5:45 
Thanks for this. It'll be an amazing starting point for my project.
QuestionCHat Program
Member 1104183427-Aug-14 21:07
memberMember 1104183427-Aug-14 21:07 
Very nice solution
QuestionBug for sending files
jonald zeine4-Jun-14 0:22
memberjonald zeine4-Jun-14 0:22 
sir.. i am confused when i sending large files and example machine A is sending zip files which is more than 5 mb i get error i dont know the exact error of that and when i send back from machine b to machine a i get the same error ..
.. can you please check and review it for me? i am using visual studio 2013 and i am modifying your code for my application to apply it to network monitoring and with a feature of chat and sending files to its client machine ..
and im am glad to see your code and sample source application and i will give it as a credit to you in my credit section of my application .. please help me. to enhance your code and make it error less and accurate in different machine.. well thanks again sir.
QuestionCan I use UnoLibs.Net.dll forever?
dinhnq20-Jun-13 15:33
memberdinhnq20-Jun-13 15:33 
i just ask you : UnoLibs.Net.dll is free license forever or someday my program will be blocked by this dll?
rfatcakr19-Jun-13 2:36
memberrfatcakr19-Jun-13 2:36 
it is so helpful Roll eyes | :rolleyes:
QuestionDatabase for Rapid Project
Irahsyairah16-May-13 14:46
memberIrahsyairah16-May-13 14:46 
hi andrew .. Can I get the database to your project rapid chat as a reference project for my final year projek .please help me andrew. thank you
Questioncan you help me?
mouse7114-Jan-13 18:07
membermouse7114-Jan-13 18:07 
i can use this program, because i have an error like this
C4F_P2PWinformControls this is missing
and My.Computer.Audio.Play(txtSound.Text) , it is said that not null
AnswerRe: can you help me?
Juan Diego Valencia26-Sep-14 5:44
memberJuan Diego Valencia26-Sep-14 5:44 
Get ir from here:[^]
Questionwho wan to help me about this software?
mouse71122-Dec-12 18:36
membermouse71122-Dec-12 18:36 
i have a some question , i can not work it,i am using vb2010,when i run it,there is always some error. i need a big help, please.
QuestionWell That's Awesome
Apoorva Gora18-Dec-12 0:45
memberApoorva Gora18-Dec-12 0:45 
Brilliant work done and really helping for us Smile | :) thanks mate.
QuestionHi Andrew
shaha412-Apr-12 23:18
membershaha412-Apr-12 23:18 
Hi Andrew>> Smile | :)

I have a project talk about chat with An Instant Messaging TCP/IP Application..but i faced many difficulties..

Can you help me?
Generalhow to I see other online users
vmaxp21-Apr-11 3:04
membervmaxp21-Apr-11 3:04 
how to I see other online users
in the current project I can only send files to myself
GeneralMy vote of 4
bagoes4all28-Dec-10 5:35
memberbagoes4all28-Dec-10 5:35 
nice.. can you post about full project sample chat like mig33 or yahoo... thanks
GeneralMy vote of 5
iamgowda16-Dec-10 23:01
memberiamgowda16-Dec-10 23:01 
Simple to use and an awesome application created out of free resources
QuestionMultithread Server
M_Amin12-Nov-10 4:19
memberM_Amin12-Nov-10 4:19 
I have a server with several clients
How do i handle server with several clients?
GeneralMy vote of 5
andersonguilherm11-Jul-10 21:11
memberandersonguilherm11-Jul-10 21:11 
GeneralMy vote of 1
Rio_Grande6-May-10 5:40
memberRio_Grande6-May-10 5:40 
Rant[My vote of 2] Incomplete coding
JSH2313-Apr-10 14:13
memberJSH2313-Apr-10 14:13 
I have had to add various coding to the source. Please do check up oin it
GeneralMy vote of 1
arkamukherjee21-Feb-10 20:18
memberarkamukherjee21-Feb-10 20:18 
18 BUGS!!!
Generalfinding dll
joesamraj7-Jan-10 21:03
memberjoesamraj7-Jan-10 21:03 
sorry, i find all the dll files in bin folder
Generalso good
Abdinoo19-Sep-09 1:57
memberAbdinoo19-Sep-09 1:57 
really so good and learned
GeneralMy Vote of 2
_Khallaf18-Sep-09 9:14
member_Khallaf18-Sep-09 9:14 
'Check to make sure that the user has entered
'a display name, and a client IP Address
'If Not, Show a Message Box

Why not grab the remote IP programatically? This is weak approach,
yet, you expect the user to be knowledgeable enough to enter anything
at all. Good Luck Big Grin | :-D

If Listener.Pending = True Then
I used to write things like these in my early VB days Wink | ;)
Listener.Pending is a function (i.e. equals the value itself)
so you don't have to compare it to another value.
This should be If Listener.Pending Then

And, yet it is not clear to me how are you handling threads?
How do you control them? There seems not to be any kind of thread
GeneralRe: My Vote of 2
slimtugo6-Sep-10 7:15
memberslimtugo6-Sep-10 7:15 
Guy you should realize that some people prefer to be verbose while others don't.
Since This
If Listener.Pending = True Then
and this
if Listener.Pending then
both yields the same result whats the big deal? The code should be very easy to understand for beginners. Give some room for those that are still in their "early VB days".
GeneralRe: My Vote of 2
Member 117382954-Aug-15 3:48
memberMember 117382954-Aug-15 3:48 
So have you recreated this program "correctly"? You are picking up on such minor points its almost like your still at school! (Are you btw?)

Also if you could read.... you'd see that this was posted back in 2009 - some 5 years before your "Miraculous" sighting of problems... Instead of criticising, perhaps write in a way that actually helps people understand the code! Or.. just keep it zipped!

GeneralMy vote of 2
_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
Donsw12-Sep-09 16:31
memberDonsw12-Sep-09 16:31 
OK article but you should explain more. how might this work over the internet, also how other chat like others have said msdn has a sample chat. other than liking to do it add something and tell why

My Recent Article : Backup of Data files - Full and Incremental

Sin Sareth9-Sep-09 23:54
memberSin Sareth9-Sep-09 23:54 
This program i don't know about your code. Please explaine me step by step.
GeneralMy vote of 1
BooGhost9-Sep-09 12:36
memberBooGhost9-Sep-09 12:36 
This code does nothing to raise the bar. It is, in fact, considerably worse than the SDK chat sample. Keep at it - someday you will learn something worth sharing.
GeneralMy vote of 1
PKBoone18-Aug-09 5:20
memberPKBoone18-Aug-09 5:20 
see messages
Generalbug number 3
PKBoone18-Aug-09 5:18
memberPKBoone18-Aug-09 5:18 

if you leave the program before you enter a display name, then you get the pop up that "all fields must be filled." It's obvious why... because the program wants to send teh message that the user can no longer be messaged.... It's a nice function... but annoying if I hadn't put in a name yet, or if I haven't even connected to anyone yet. I suggest setting a default display name such as "Anonymous".
GeneralBug number 2
PKBoone18-Aug-09 5:14
memberPKBoone18-Aug-09 5:14 

if you click the "clear" button, then the message "Writing message..." appears in the message bar.

there also seems to be a missing image on the right side of the tool bar. I only see the missing image symbol. Same goes for the demo.
GeneralRe: Bug number 2
Andrew Courtice18-Aug-09 15:33
memberAndrew Courtice18-Aug-09 15:33 

Just to clear up the confusion.

There is no image missing from the toolbar. During debug i set an image in that picturebox, which would have automatically saved in the my.settings class during the form close event. so when you started the application on your computer, the my.settings class would be looking for a location on your computer which does not exist.

I should have deleted all of my user settings before i uploaded the solution. sorry bout that.
GeneralMissing Message.png file in Source
PKBoone18-Aug-09 5:08
memberPKBoone18-Aug-09 5:08 
I hate to be nit picky but I am starting to get disappointed... The Message.png file is missing from the source download.
GeneralMissing error correction
PKBoone18-Aug-09 4:57
memberPKBoone18-Aug-09 4:57 

I don't know if you did this on purpose, but all of your functions and subs are missing error correction.

first bug:

click on the image button and then cancel out of the dialog. you will get a runtime error.

you need to delete the code line:

and change the code line:

If DialogResult.OK Then


If ofdImage.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then

The problem your code has is that "DialogResult.OK" always = true. In other words you forgot to assign the result of the ofdImage.ShowDialog to the Dialog.OK variable.... wich you can't do anyway because it is a system constant.

I know that

"If ofdImage.ShowDialog(Me) Then"

would work too, but I think it's better to add the condition for clarity.
Also, one more oppinion if you don't mind....

when a user cancels out of the image function.. don't replace the picture with an Error Image... Why not? What if a user just clicks the button to see what happens, then decides not to change the picture? You are punishing the user for changing its mind.
GeneralRe: Missing error correction
Andrew Courtice18-Aug-09 13:09
memberAndrew Courtice18-Aug-09 13:09 
Thanks PKBoone for your feedback. I've fixed the bugs you mentioned and gone over the code again checking for errors. I've also added the class library's and images in the source project. I apologise for the inconvenience.
GeneralMissing assemblies
PKBoone18-Aug-09 4:35
memberPKBoone18-Aug-09 4:35 

nice job, however some of the assemblies are missing in the source. Which means I have to hunt them down myself....

GeneralRe: Missing assemblies
PKBoone18-Aug-09 4:42
memberPKBoone18-Aug-09 4:42 
yeah, okay... the DLL's are in the Demo Download Zip. But for the sake of simplicity they should also be in the Source Zip... don't you think?
GeneralRe: Missing assemblies
joesamraj7-Jan-10 21:02
memberjoesamraj7-Jan-10 21:02 
can you please tell how to get that missing assemblies
GeneralLooking good!
Ant210012-Aug-09 2:06
memberAnt210012-Aug-09 2:06 
Wow, I'm loving this one! I've thought for ages about chat programs, and maybe integrating chat windows into some applications I have. I'll study this code carefully Smile | :)

5 points from me Wink | ;)



Check out my desktop conversion software for Windows -

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

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