A Client server Chat program using the Winsock control

Level:
Level2

See how easy it is to create a simple chat program. This tutorial explains how to create both the client and server sides of the program using the Winsock control.

In this tutorial we will learn how to write a simple client server chat program in Visual Basic 6 using the Winsock control. We will right both the server and client side of this program. One of the ways computers can communicate to each other through the internet is by using TCP/IP. In windows there is a Winsock.dll that programmers can leverage to help in this communication. This DLL is very annoying to use in Visual Basic. Luckily, we can use the Winsock control instead - which wraps a lot of the Winsock.dll commands into an easy control for us.

You might want to download the source code for this tutorial .

To start lets create the client side of our program. Open a new Visual Basic 6 Project (Standard EXE). In order to use the Winsock control we must add it to our toolbox. You can do this by selecting Project -> Components from the menu bar or by pressing Ctrl-T. Then click the check box next to the Microsoft Winsock Control 6.0.

VB6 tutorial screenshot 1

Now on Form1 create the following controls with the following property values

Type: Winsock
Name: sockMain

Type: TextBox
Name: txtHost
Text: 127.0.0.1

Type: TextBox
Name: txtPort
Text: 12345

Type: TextBox
Name: txtStatus
MultiLine: True
ScrollBars: 3 - Both

Type: TextBox
Name: txtSend

Type: CommandButton
Name: cmdConnect
Text: &Connect

Type: CommandButton
Name: cmdSend
Text: &Send

Add some labels to organize stuff and arrange your form to look something like this:

VB6 tutorial screen shot 2

Now lets write our code
Double click on the Connect button and add this code:

Private Sub cmdConnect_Click()
   sockMain.RemoteHost = txtHost.Text
   sockMain.RemotePort = txtPort.Text
   sockMain.Connect
End Sub
This code is pretty easy to follow. We just setup our socket to point to the remote host specified and the remote port, and then we tell it to connect.

Next wire up the Send button:
Private Sub cmdSend_Click()
   sockMain.SendData txtSend.Text
End Sub
Again very simple, all we do is Winsock control to send the data we want it to. Next we will want to receive data when the other person sends it to us. The Winsock control again makes this easy. Every time data arrives the Winsock controls DataArrival event will fire. So lets wire in our code for that.
Private Sub sockMain_DataArrival(ByVal bytesTotal As Long)
   Dim strData As String
    
   sockMain.GetData strData, vbString
   txtStatus.Text = txtStatus.Text & _
      strData & vbCrLf
End Sub

So in this event we call sockMain.GetData. This method takes two parameters. The first is the variable to store the data in. The second is what type this variable is. Once we have our strData variable filled we append it to status textbox.

Server Side of VB6 Program 

Now lets create the server side of our program. Normally you would create a new Visual Basic program just for the dedicated server, but to make things easier we are just going to create a second form. So add a Form2 to your project. And add these controls to it.

Type: Winsock
Name: sockMain

Type: TextBox
Name: txtPort
Text: 12345

Type: TextBox
Name: txtStatus
MultiLine: True
ScrollBars: 3 - Both

Type: TextBox
Name: txtSend

Type: CommandButton
Name: cmdListen
Text: &Listen

Type: CommandButton
Name: cmdSend
Text: &Send

The way a client server relationship works is that the server listens on the port specified. Then when a remote computer (the client) connects to that server at the specified port the server creates a connection with the client and they can communicate back and forth. This is why the server does not have a txtHost text box - because he will listen for any computer that wants to connect.

So lets write our Listening code:

Private Sub cmdListen_Click()
   sockMain.LocalPort = txtPort.Text
   sockMain.Listen
End Sub

That’s it - when the user presses the listen button sockMain will start listening on the port specified. Now lets move on in our tutorial. Next we will write the code to handle an incoming connect. When someone connects to the port we are listening on we have to decide what to do with him. We do this in the Winsock controls ConnectionRequest event.

Private Sub sockMain_ConnectionRequest(ByVal requestID As Long)
   If sockMain.State <> sckClosed Then
      sockMain.Close
   End If
    
   sockMain.Accept requestID
    
   txtStatus.Text = txtStatus.Text & _
      "Accepted connection from: " & _
      sockMain.RemoteHostIP & vbCrLf
End Sub

The Socket controls ConnectRequest event passes with it a requestID - this identity's who is trying to connect. This is very useful if you are allowing more than one connection. Since in this basic tutorial we are only allowing one person to connect at a time our code is very simple. First we check to see if the connection is already open we just accept the connection. Then we write a line to our status box se we know.

Lastly lets wire up our send button and our data arrival event for Form2 like we did for Form1:

Private Sub cmdSend_Click()
   sockMain.SendData txtSend.Text
End Sub
   
Private Sub sockMain_DataArrival(ByVal bytesTotal As Long)
   Dim strData As String
    
   sockMain.GetData strData, vbString
      txtStatus.Text = txtStatus.Text & _
      strData & vbCrLf
End Sub
Also add a quick line of code in the Form1 load event to show Form2 as well.
Private Sub Form_Load()
Form2.Show
End Sub

Now lets test out our program. Press F5 to run it. Then click the listen button on our server (Form2). Next click the connect button on our client (Form1). Now the two forms can chat back and forth. If you would like you can download the source code for this tutorial .

This tutorial explained how to create a simple client server connection. If you would like to expand upon this make a server that allows multiple clients to connect to it check out this tutorial: A multiple client server chat program using Winsock control.

If you enjoyed this post, subscribe for updates (it's free)

Requesting to teach file transfering

Hi! I am Digganta Mandal. I am new to Visual Basic 6.0. I request you to mail me a code in vb6.0 which teaches us to transfer files using Winsock control. My email is : digantamandal28@gmail.com
Thanks in advance....

Send emotion in chat program

I want to send smiles with text.

Please tell me how can i do that

Game Detector

Hi! im just a college student, but im creating a program that can detect a "GAME" running!

for example, an office worker plays a game while in working hours.

can the VB6 detect the game, saves the time the game starts, and saves the time the game teminated ?

then the time(game starts) and time(game stops) be SENT to the admin ??

if it can be done, can you please help me ?

i really need help, email me if you can: johnaxlmalanum@yahoo.com

thanks in advance!

btw nice web site here! i like it here :D

VB6, Server & Client programm.

This web site is amazing. I like it very much. Above code is very exact, No doubt about that.
It's very important site for programmer.

smtyms it's not workin'

Hey man the tut. Is pretty awsm, but smtyms when i try to listn and cnnct it simply does'nt work,i'm using w7 x64 an VB6 and i've added the line

    on error resume next

on every sub,hope u'd undrstnd what the prblm is. Thnx in advnc.

cannot send msg from server

this is what i retype on client coding part
Private Sub cmdConnect_Click()
sockMain.RemoteHost = txtHost.Text
sockMain.RemotePort = txtPort.Text
sockMain.Connect
End Sub

Private Sub cmdSend_Click()
sockMain.SendData txtSend.Text
End Sub

Private Sub Form_Load()
Server.Show
txtSend.Text = ""

End Sub

Private Sub sockMain_DataArrival(ByVal bytesTotal As Long)
Dim strData As String

sockMain.GetData strData, vbString
txtStatus.Text = txtStatus.Text & _
strData & vbCrLf
End Sub

and this one is for server coding part:

Private Sub cmdListen_Click()
sockMain.LocalPort = txtPort.Text
sockMain.Listen
End Sub

Private Sub cmdSend_Click()
sockMain.SendData txtSend.Text
End Sub

Private Sub sockMain_ConnectionRequest(ByVal requestID As Long)
If sockMain.State <> sckClosed Then
sockMain.Close
End If
sockMain.Accept requestID
txtStatus.Text = txtStatus.Text & _
"Accept Connection From : " & _
sockMain.RemoteHostIP & vbCrLf

End Sub

Private Sub Form_Load()
txtStatus.Text = ""
txtSend.Text = ""
End Sub

Private Sub sockMain_DataArrival(ByVal bytesTotal As Long)
Dim strData As String

sockMain.GetData strData, vbString
txtStatus.Text = txtStatus.Text & _
strData & vbCrLf
End Sub

.....

and what i get is i cant send back messages from server.. anyone please help me on this?

once connection is

once connection is established u can send data to any side

Private Sub cmdSend_Click()
sockMain.SendData txtSend.Text
End Sub

i wrote the code, but i cant

i wrote the code, but i cant send messages back and forth from either side, whatever i do, i just get a 40006 error, saying "wrong protocol" or something like that. After clicking debug, its highlighting this line : sockMain.SendData txtSend.Text . please help, dont know wat to do...

You're probably getting that

You're probably getting that error because the client and server weren't connected when the application tried to send the data. Throw an If-Then before the senddata call that simply checks if the socket is connected.
Such as: If Not SocketName.State = sckConnected Then Exit Sub

Hello. I will make program

Hello. I will make program chat for internet. I think, your code only for local network. I will connect by email address. Pleace, help me?

TCP PACKET

How Can we make Over Own TCP packet?

424 run time error

hey im getting "424 run timr error " on connect.
also what port no shud i include???/
waitn 4 ur reply>>>!!!

Heavy programming in the VB6 DataArrival event causes hangs

I am upgrading an existing VB6 program to use a socket interface. I have experienced ongoing hangs which I have narrowed down to having a heavy programming path (e.g. DB access) in the DataArrival event. I have tried using a memory queue and a timer to fire off another thread but I still get hangs. It appears that if the program is too busy to process the DataArrival event the interface to TCP just hangs and only the task manager can kill the process. Any ideas on how to get round this?

Inquiry?

is Winsock control support external network? i mean outside my Local area network..... is it possible i can access my database in my server if I'm trying to Connect outside my local area network... i did a simple system.. its working on my LAN network. NO PROBLEM.. its working fine... but when it comes to WLAN it sucks..

guys.. need HELP.. give me some examples.. or demo on how to set my simple system.. so i can connect to my database anywhere..

or send me and email aries.suson@yahoo.com

tnx in advanced.

thank u it was so

thank u it was so usefull
specially "If Winsock2.State <> sckClosed Then Winsock2.Close"

vb project

hey friend............!!!
iiiii am the student of poly, i am making a vb project but but i dont know to connect it to internet, so if possible can u help me, i want to make it online available so if u have any simple coding example in which uuuuuuuuuuu have done it please send it to meeeee,
i will very thankfull to uuuuuuuuu
gaurav.............

Umm ya i get a 424 error

Umm ya i get a 424 error

sckClosed and sockMain.State are having errors

when i implemented the winsock connection request, it gave me error messages;
"'state' is a type in ' AxMSWinsockLib.Axwinsock and cannot be used as an expression" and
"'sckclosed' is not declared" what type of variable is this going to have.
I am using vb2008. Thanks

Via Online

hi! just would like to ask.. can i connect two computers using internet?? i mean can it be online? or only LAN? thanks

i like the tutoria

i just want to say, i am enjoying this, infact, i have gained so much from this tutoria and i hope to contribute some day, God willing. thanks

Vb6 Crashing

When i compile, run, or Exit Vb6 Crashes.....

What do I do,,,,,,,,,,,,,,,,But great tutorial....

Do you know how to put buzz alert, stealth settings?

Do you know how to put buzz alert, stealth settings,file transfer and webcam to this chat program???

that missing Winsock OCX

Found a solution here -

http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/93ff8529-3540-47b3-a05a-2c8a81922f40

it seems to work, as has added the component to the form toolbox. Takes a while to load all the components in before selection can be made.

Right-click on the open form Toolbox menu, and select 'Choose items...',

when it loads select the Microsoft Winsock Control from the COM tab, and it'll be added to the Toolbox.

um there's no Winsock control

Using Visual Studio 2010 Professional - there's no Winsock Control to select on any of the form components,

and the online search for components can't find anything with 'winsock' in it either.

Is it renamed in 2010? Can something else be used instead?

close visual basic 2010 and

close visual basic 2010 and right click on the icon and click run as administrator
when it opens go to the tool box and right click then click choose items.
at the top of the "choose toolbox items" window click on the "com components" tab then click browse down the bottom. in the dialog box that pops up navigate to "C:\Windows\System32\MSWINSCK.OCX"
then click ok
the winsock control should be visible in the list
make sure it has been ticked

RE: um there's no Winsock control

There is no Winsock component in 2010, as it's been not available ever since VB programming came to use the .NET Framework. Now you have to use the System.Net namespace built-in. It's been giving me problems ever since I started using Visual Basic 2008, where it was easier to do with VB6.

Hello

Why is the remote host set to 127.0.0.1 can I change i to send via LAN on another computer

127.0.0.1 is a loopback

127.0.0.1 is a loopback address. Meaning, you can only sent data to your own PC unit.
Yes, you can use other IP address to access the other PC unit that is a member of the Network.
But make sure that the IP address is a valid address!

Anyone tell me how to do

Anyone tell me how to do this with AxMSWinsock 2005? I am using VB 2008.

Errors on ConnectionRequest, RequestID is not part of the object; If sockMain.State <> sckClosed Then isn't correct.

WinSock with LAN connected to Internet

The Tutorial is great.
How can data be send from one computer using LAN connected to Internet at server, to another computer connected to internet using Winsock control
Thanks

Grate Tutorial

Hey! Gr8 Tutorial for Newbies just like me :). Working fine.Keep it Up.

multi-client

thnx for the code
i want to ask one thing......
how can i modify this application so that there is one server and 10 clients
so that each client can directly communicate with the server........not with the other clients.
plz reply as soon as possible.

RE: multi-client

You'd have to make a control array with the Winsock controls, to accept each connection, for the server. As for the client, just leave it as-is.

hi, I want 2 ask u is it

hi, I want 2 ask u is it possible that the data v are sending 2 the server or remote host can be saved in a database maintained by server if yes then how is it possible
my project requires the client machine 2 send department and employee details on server machine which should then be saved!

RE: hi, I want 2 ask u is it

You'd have to code the server to directly access the database, or use a external application that does the database.

local network chatting

hey, i tried your code and it worked great, however, i wanna ask about the code on how to chat with other work stations over the network using this system..thanks..:)

Runtime error 40006

If i tried with two pc chat application worked,But i cann't send the message from one more pc in this network.I am getting "Wrong protocol or connection state for the requested transaction or request" error while sending message from another user's pc,at the same time two person can chat. How can i resolve this error.

People who are getting 40006

That simply means that the socket is still connected and you're trying to reconnect as it's still connected.
I noticed that his code doesn't have the code to prevent that.
If you want the answer to this...

Make sure you do not forget the
"if winsock1.state <> sckclosed then winsock1.close"
and above that include the line
"On error resume next"
Should be good then. :]

this code is very simple to

this code is very simple to understand and you have made it step by step so that a newbie can easily learn the concept.
Thanks a lot.

Error 40006

I just hope this is not quite late..I guess there is no problem in the codes, the thing is click first the listen button of the server form to open the port for any request..I hope I did help somebody..thanks!

10 minutes, from scratch to tested

As it's already late here, i'll look at the more advanced version tomorow, than maybe add some stuff for my friends and I. Your tutorials make transition from VB3 (that I was using many many YEARS ago) very smooth. Good job, I'll click on the commercial banners as a thank you ;)

Send & Get Text

Hi
im sorry for my english lanquge not good .
i want to bold or italic text and send to client or server
how in client or server get text with bold or italic ,... shap

Tnx

CHat Appication

Hi,Actually i have tried this application,it is working fine on my machine .But i have built two exe and Server exe is placed on my friend's machine (which is in network).Client exe is placed at my system.In Host text box i have added IP address of my machine and port number.My friend added port number and clicked on Listen then i clicked on Connect still it is giving error "40006"

Please tell me what to do???

ggfg

fsfss

run-time error 40020

how to fix run-time error '40020'?

abc

By closing that program you can avoid this type of errors

error Runtime 40020

how to fix this problem "run-time error'40020' : invalid operation at current state

40006 error

I keep getting the 40006 error message; I think it Might Be the IP Port.
How Can I Change My IP address

Run time Error 40006

Hi!

I tried all options to get rid of this run time error 40006 but still occuring.Please tell me what should i do.

Thanks in advance.

Run-Time Error 40006

i get runtime error 40006 "wrong protocol or connection state for the requested transaction or request." when i lcik the send button on both client and server. This happens in the source code download aswell. How can i fix it?
On both when i click debug it hightlights the cmdSend section of the code.

cmdSend_click() error fix

change this:

Private Sub cmdSend_Click()
sockMain.SendData txtSend.Text
End Sub

TO THIS:

Private Sub cmdSend_Click()
sockMain.SendData (txtSend.Text)
End Sub

its works then.

Winsock

I am getting the same error message. I have tried everything, including upgrading to SP6. Have tried other versions of the same type of code from msdn, but still the same problems. I am at a loss.

hey

Ummmmm I did this once using your steps and worked beautifully. Thx tried using Youtube and always got an error. No problems with this one.

Port

Dear,
sorry for my stupid questions :

- the 127.0.0.1 in the example is the local host (my PC?) and the port number is just a virtual one (always on my PC?)
- in real case, what have I to set up on my server (IP: 62.149.140.18)
- which port have I to assign for chatting?
- asked my provider, I was told that with shared hosting I cannot set-up any special port
- does it exist on internet some service letting me to use their server and a reserved port for my private cha application?

Thank you in advance.
Maurizio Ammannato

NETWORK PROTOCOL

IP: 62.149.140.18?

why use a "class A" network Protocol?
IF YOU WILL USE IT ONLY FOR LESS THAN 30 COMPUTER UNITS, JUST USE "CLASS C" network Protocol.
CLASS C:
192.0.0.1 ABOVE.

Name

i got a name box in my chat. how do you get the name to say when you connect and speak? like msn it says the name then says what they want to say...

Name

i got the answer already but i cant get the things i type to go into my own text box like in form 2... i have a box called txtStatus and when i type stuff into txtSend and press send it just sends it to the other person i am talking to not me. plz help

It only sends it to the

It only sends it to the other person because that is what the code tells it to do. Why don't you in the send buttons click event have it send the text to the other person and then simply append that text to your text box?

NVM

nvm i got it to work but my close function... dosent work. i use the same prog for the 2 person chat and when i connect then close it only tells ME that the connection is closed but the other perrson dosent

some help

well i did it so that it is like this , when you hit the button it adds it in front of it as it goes into the main chat area , i m not on my vb6 pc atm but i think the code is something like this,
private sub cmdsend_click()
dim text&name as string
text&name = vbcrlf & name & ":" & txtsend.text
' and then it goes something like the original code
sockmain1.senddata (text&name)
' or whatever that is supposed to be , hope it helps

I am new

Just getting back into this after being out a while!! When I run this script, I keep getting a complie error "varible not defined" In the area marked by the astrix

""Private Sub cmdConnect_Click()
sockMain.RemoteHost = txtHost.Text
sockMain.RemotePort = txtPort.Text
sockMain.Connect
End Sub

Private Sub cmdSend_Click()

*****Private Sub Form_Load()
Form2.Show

txtStatus.Text = ""

End Sub******

Private Sub sockMain_DataArrival(ByVal bytesTotal As Long)
Dim strData As String

sockMain.GetData strData, vbString
txtStatus.Text = txtStatus.Text & _
strData & vbCrLf
End Sub

Winsock

sockMain
It will list the txtStatus.Text ="" as the varible not defined???? Can someone explain this to me?? Or what I'm missing??

My Opinion

This is very good and works, if you are having problems with the 40006 error like I did just read the comments ;)

end connection?

what would the code be for a button to terminate the connection, instead of having to close the program each time?

Just add a button and in the

Just add a button and in the click event call sockMain.Close()

thanks for the reply..is

thanks for the reply..is there any way to use winsock control and create client server netwrking?im new to vb,..

im using vb 2005....can i

im using vb 2005....can i use this code for vb 2005..i have try them out...but there a few errors saying...

1) Error 1 'State' is a type in 'AxMSWinsockLib.AxWinsock' and cannot be used as an expression.

2) Error 2 Name 'sckClosed' is not declared.

can pls help me if there's another way of doing this..thank you..

This code will only work

This code will only work with VB6 - sorry. I am working on VB.NET version of this website, but it will probably be a while before its done. Check out my review of this VB.NET Tutorial site. You might find it helpful.

How can you tell...

How can you tell what version you have? Mine says Visual Basic 2008 Express Edition. Is that VB6, VB.Net or something totally different

Also... There is a problem in the code:

If sockMain.State <> sckClosed Then
sockMain.Close()
End If

It Highlights SockMain.State and sckClosed

It says something about SockMain.State cannot be used in an expression. And sckClosed not defined.
Should I update my code???

I was just wondering if it

I was just wondering if it was possible for you to add how to use screen names so that it isn't confusing when people type, and also so you are able to see your own text when you send it out. Overall good tut :)

uh this sux...

this one isnt so good...i saw a better one but you cannot use this with 2 computers. I need to no how to connect and build a online server

forgot...

hi just to let you know you forgot to put txtStatus locked=true if you dont do that you could easly lose all your convosation.
and i was wondering if you could tell me how to make a line break after each message and maybe time the message was sent?

P.S thanks so much for all the help iv been wanting to do this for ages. i love your website

just add a text box and on

just add a text box and

on your send it should look something like this double click the textbox u use for chatting and paste this in

Private Sub Text2_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then 'if we press enter then send text and clear the chat textbox after text is sent to the chat
Winsock1.SendData (Nick.Text + ":" + ChatSend.Text)' u will need to put the correct names of your textboxs where mine are called nick & chatsend
ChatSend.Text = ""

'this will allow u to put a Nickname in one textbox and type in another

i.e) Nick:Hello all .how is everyone?

Nice

This will help when I code the multiplayer part of my game.
~ZaerTheDraconian~
PS: Would it be possible to put chat in a listbox? It would be easier to add chat items that way. Also, would it be possible to put the cmdListen Click code in Form Load? Thanks in advance.

Run-Time Error 40006

i get runtime error 40006 "wrong protocol or connection state for the requested transaction or request." when i lcik the send button on both client and server. This happens in the source code download aswell. How can i fix it?
On both when i click debug it hightlights the cmdSend section of the code.

Sorry

Sorry I probably should have explained this. First you need to Click the Listen button on the server. This will start the server listening. Then press the connect button on the client. This will tell the client to connect to the server. Once those connections are made then you can send stuff back and forth. Hope this helps.

2 exe's

How do you make 2 different exe's? such as i have the server.exe and they have the client.exe

Thx in advance

Two exe's

How do you make 2 exe's so that i have the server.exe and they have the client.exe? Please tell me how to make 2 different files

Thx

Dump

Dear I Think You Are New In VB
For Server:-
To Create Two Exe For This Lovely Application simply Make Sure that the Form you wants to use as server sud be at start up of project
For Client:-
To Create Two Exe For This Lovely Application simply Make Sure that the Form you wants to use as Client sud be at start up of project

to do this Go to Project>>Project1 Properties>>>startup opject ....

How to make two Exe's

Open each form separately and compile them to exe's.

using two text box...

how can i use it in two text or more box to send and in other pc two or more textbox to recieve?? thx in advanced

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo].

More information about formatting options

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.