News Button Separator General Button Separator   Tutorials Page Side Products Page Side Gallery   Button Forum Button About
Tutorials


GamerTheGreat.com - The Best Flash Games/Animations Portal for Great Gamers. Are you Great enough?



 

..........Visual Basic 6 Winsock Tutorial - Part 1

by VirusFree

 

 

Tutorial Description :This tutorial will teach you how to use Winsock in Visual Basic 6 to create
Internet/Intranet Connections. You will soon find out that learning how to
manipulate the power of the net will not only be very very exciting but also
open your horizon to a new world world of software capabilities
It's also really really cool

 
Who should read this :This tutorial targets the beginners in Visual Basic 6. This is a very very basic
tutorial and should not be read by anyone who knows the basic of connect,
send and receive with Winsock Although i will try to explain everything as
thoroughly as i can, basic knowledge of visual basic 6 or generally
programming is required.

 
What is Winsock :The Winsock we are going to use is an ActiveX that we can add in our
visual basic program so we can use it's features. When using the internet
( like from a web browser ) a lot of things happen behind the scenes.
Packets are constructed by the soft wares that are then being send through
routers and others are being received by your Operating System and analyzed
by the application that send it. In order to do such complicated things a lot
of in formation like headers, packet size ,hashes ,packet order and many more
are required to create the packets. You WILL NOT have to deal with that stuff
using the Winsock control from vb. Continue reading to see just how easy it is
to effectively use Winsock.

 
What do you need :For this tutorial you will only need a computer running Windows ,
Microsoft Visual Basic 6, and the will to learn!

 
What will this tutorial teach you :In this tutorial i am going to show you how to create a simple chat program.
The chat program will be just a server and a client, that you can connect
from the internet ( or LAN ) and simply exchange text messages.

 
What are servers and clients : To connect any 2 programs, you need at least one server and one client.
The server will be the program that opens the ports on the hosting machine
and receive the connections while the client is called the program
thatconnects to the remote host. For example, when you connect to Google
withyour firefox (or  internet explorer), your browser plays the role of the client
that connects to the hosts that are running at Google. Most common is for the
servers to be able to receive more than one connections from different clients
These is called multithreaded socket servers , but I am not going to show you
how they are made in this tutorial, just to keep things simple. What i am going
to show you is simply 2 applications connecting together, and sending/receiving
text strings.



 



 
 

   Download the Tutorials Example Source Code   


 
 
Writting the Client
 
First create your client form..
 


 

 
Now we have the form but it has no code inside, it's only the components.

Remember that you need to add Winsock ActiveX control to your program,
to do this right click on the toolbar that is left to the form ( where buttons ,labels... are)
Then click on the "Components..." item from the menu bar and find "Microsoft Winsock Control 6.0"
Select it and click ok
 
We will start by writing the code needed for the 'Connect' button to work.
 

Private Sub bntConnect_Click()
On Error GoTo t

'sock1 is the name of our Winsock ActiveX Control

sock1.Close 'we close it in case it was trying to connect

'txtIP is the textbox holding the host IP
sock1.RemoteHost = txtIP      'set the remote host to the ip we wrote
                                                'in the txtIP textbox


'txtPort is the textbox holding the Port number
sock1.RemotePort = txtPort     'set the port we want to connect to
                                                '( the server must be listening on this port too)


sock1.Connect 'try to connect


Exit Sub
t:
MsgBox "Error : " & Err.Description, vbCritical
End Sub

 
 
This code is pretty commented so it is not hard to understand. What we are doing here is closing
the Winsock before trying to connect ( because if it was already tying to connect and we call connect
again we will get an error ), the we set the appropriate variables ( IP and Port ) and call the connect function

 
The Connection :

-  We now have finished the code behind the connect button , so when you click it it will try to connect to
    the specified host on the specified port. Now we need ( not absolutely necessary ) to know if the connection
    what successful.

-  The Winsock control has an event called sock1_Connect , this events will be triggered if we have a
    successful connection. All we need to do here is to clear the chat buffer and put a message that says
    that we have successfully connected to the remote host

 

Private Sub
sock1_Connect()
'txtLog is the textbox used as our
'chat buffer.

'sock1.RemoteHost returns the hostname( or ip ) of the host
'sock1.RemoteHostIP returns the IP of the host


txtLog = "Connected to " & sock1.RemoteHostIP

End Sub
 
 
 
The Failure :
 
-  Connection on the remote host could failed for many many reasons
         - Hostname or IP is invalid
         - Host doesn't accept any connections on that specific port ( port is closed on the host )
         - Error in Internet connection ( you are not connected or for a reason can't reach host )
         - Host is down/offline
         - Connection Lost while you were connected to the host
         - ...

-  To handle this errors you need to use the sock1_Error , which also gives you many information about
    the error. The most important are Number and Description.
 

Private Sub sock1_Error(ByVal Number As Integer, DescriptionAs String, ByVal Scode As Long,ByVal Source As String, ByVal HelpFileAs String, ByVal HelpContext As Long, CancelDisplay As Boolean)

'this event is to handle any kind of errors
'happend while using winsock

'Number gives you the number code of that specific error
'Description gives you string with a simple explanation about the error

'append the error message in the chat buffer

txtLog = txtLog & "*** Error : " & Description & vbCrLf

'and now we need to close the connection
sock1_Close

'you could also use sock1.close function but I
'prefer to call it within the Sock1_Close functions that
'handles the connection closing in general


End Sub
 

 
Connection Ending :
 
-   There is an events that is being triggered every time the connection closes. This
     event is sock1_Close
 

Private Sub sock1_Close()
'handles the closing of the connection

sock1.Close 'close connection

End Sub
 
 
 
Sending Data :
 
Data sending is a very important part of the connection. You can send a string to the host simply
using the SendData function of winsock. Bellow is the code that we must wrote for the Send button
to work.   
 

Private Sub bntSend_Click()
On Error GoTo t
'we want to send the contents of txtSend textbox

sock1.SendData txtSend 'trasmits the string to host

'error handling
'( for example , we will get an error if try to send
' any data without being connected )

Exit Sub
t:
MsgBox "Error : " & Err.Description
sock1_Close 'close the connection
End Sub
 

 

A lot of hard work is behind everything you see in this site. So if you like it please make a donation
Receiving Data :
 
Data receiving is as important as the data sending. With Winsock things are really easy.
All you need to do is to use the GetData function of Winsock inside the DataArrival events
that is being triggered every time new data arrives
Bellow is the code that handles the new data and writes them in the chat buffer
 

Private Sub sock1_DataArrival(ByValbytesTotal As Long)
'This is being trigger every time new data arrive
'we use the GetData function which returns the data that winsock is holding

Dim dat As String 'where to put the data

sock1.GetData dat, vbString 'writes the new data in our string dat ( string format )

'add the new message to our chat buffer
txtLog = txtLog & "Server : " & dat & vbCrLf

End Sub
 
 



 
 


Writting the Server
 
Basically the server is pretty much the same as the client. I will only mention the differences.
The working server code is included in the example source code that you can download
 
Here is the Server Form

 


 
The first difference is in the Connection. While the client set a remote ip and a remote port and tried
to connect on them, the server only needs to set a local port and listen to it

Listening on the port means that the program is monitoring for any connection request made
by the clients on that specific port.
 
This is what you must do for the 'Start Listening' Button
 

Private Sub bntListen_Click()
On Error GoTo t

'sock1 is the name of our Winsock ActiveX Control

sock1.Close 'we close it in case it was listening before

'txtPort is the textbox holding the Port number
sock1.LocalPort = txtPort   'set the port we want to listen to
                                           '( the client will connect on this port)


sock1.Listen 'Start Listening

Exit Sub
t:
MsgBox "Error : " & Err.Description, vbCritical
End Sub
 
 
Now the next difference from the client is in the connection handling.
The client had the Connect event that was triggered when the connection was established


With the server we need to accept the request from the client before the connection is completed
To do that we use the sock1_ConnectionRequest that is triggered when a client tries to connect on our host.
the connection will be completed only if we accept the request. ( command is bellow with bold fonts )
Bellow is the code that handles the connection request
 
 

Private Sub sock1_ConnectionRequest(ByVal requestID As Long)
'txtLog is the textbox used as our
'chat buffer.


'this event is triggered when a client try to connect on our host
'we must accept the request for the connection to be completed


'just check for socket state
If sock1.State <> sckClosed Then sock1.Close

'with this we accept the connection and we are now connected to
'the client and we can start sending/receiving data

sock1.Accept requestID

txtLog = "Client Connected. IP : " & sock1.RemoteHostIP & vbCrLf

End Sub
 

 

 

   Download the Tutorials Example Source Code   


 


This was part 1 of the tutorial, in the next part i will show you how to create a multi-user chatroom  (just like IRC)

Click Here to go to Part 2 >>>>
 


 
This tutorial was written by VirusFree.

Thank you for reading  it and please excuse my English

For any problems or question please don't hesitate to post them in our forums
and i ( or anyone else who can answer them ) will reply as soon as possible

Keywords : winsock , visual basic , winsock tutorial, winsock tutorial for visual basic , sockets , internet , connect
 
 




    Comments
 

 VirusFree - 11/6/2006 3:37:12 AM
   
 Post here any comments/suggestions/questions/problems about the tutorial
 
 
   
 

 shadow - 11/6/2006 4:30:02 PM
   
 Nice tutorial... very well explained
 
 
   
 

 Arxwn - 11/12/2006 8:37:49 PM
   
 excellent tutorial if i may say
 
 
   
 

 Neko - 1/26/2007 1:42:37 PM
   
 Quite good. Some errors for me but easy fix =] Is there a possibility for a tutorial for a multi-user chat? And maybe an RTF so you can use colors and whatnot? Would be nice.
 
 
   
 

 VirusFree - 1/26/2007 2:52:19 PM
   
 [quote:842d73f771="Neko"]Is there a possibility for a tutorial for a multi-user chat? [/quote:842d73f771]

very good suggestion!!
 
 
   
 

 Neko - 1/26/2007 7:08:46 PM
   
 If needed, I can help you with that =] Im getting really good with winsock lately =] And im pretty good with VB all around.
 
 
   
 

 VirusFree - 1/31/2007 12:13:59 PM
   
 [quote:481ac35489="Neko"]Is there a possibility for a tutorial for a multi-user chat? Would be nice.[/quote:481ac35489]

ok! part 2 of the winsock tutorial is out!

Enjoy!
 
 
   
 

 nowhere - 2/22/2007 9:22:04 AM
   
 Hi everyone.
At first thank you for the nice tutorial.
Unfortunately i am a total beginner and so i've got some problems getting it run correctly.
My problem is, that i want to run the client Software on a windows mobile device.
Therefor i created a new DeviceApplication for intellegent devices, typed the code in, included the Winsock Component and tryed to debug.
i get the errormessage "AxHost is not included in the namespace System.Windows.Forms"
I hope this ain't a too stupid Question, but i don't know how to include it.

I hope, that someone is able to help me and sorry for my terrible english.
 
 
   
 

 nowhere - 2/22/2007 10:47:01 AM
   
 Itīs me again.
Just found the note that compact framework doesn't support axHost.
What else can i use?
 
 
   
 

 VirusFree - 2/22/2007 11:27:19 AM
   
 Just to be clear... the tutorial is NOT for .NET ..
the tutorial is for visual basic 6

in what language are you trying to write? C# or VB.NET?
because there is a C# winsock tutorial here
 
 
   
 

 nowhere - 2/22/2007 12:05:03 PM
   
 I'm developing in c# and also used the c# tutorial & sc to understand the socketprogramming.
i just recognized that i posted on the wrong thread.
Unfortunately this won't solve my problem. Are you also keen on programming in C# or should i post somewhere else on this forum?
 
 
   
 

 flippedsk8er - 3/24/2007 7:10:38 PM
   
 very nice! i have a question though..

Im new to winsock connections so im not quite sure how to get this to work. I sent the client to my friend and we were trying to connect but what port should i go on? Also does it need to be linked to the server to work?

Thanks for the awsome tutorial! -Taylor
 
 
   
 

 VirusFree - 4/10/2007 9:28:39 AM
   
 one of you , either you or your friend must have the server running and open a port on his pc.. the other one has to open the client and connect to his friends IP on the port that your friend has opened

( the one who has the server running has to also make sure that other people
can connect on his pc in case he is behind a firewall or a router or something )
 
 
   
 

 bheesham - 8/2/2007 9:36:53 PM
   
 Thank you!!! This works for me.. this is like the 20th Chat room tut for VB and so far this is the only one that works for me!!! thank you...
 
 
   
 

 computbill - 8/16/2007 9:48:07 PM
   
 Well done. I'm using winsock to request data from a remote server. Somehow, I'm losing data. What happens if you are reading received data when more data arrives? thanks
 
 
   
 

 VirusFree - 8/22/2007 1:24:04 PM
   
 [quote:40b7199a54="computbill"]What happens if you are reading received data when more data arrives?[/quote:40b7199a54]

You shouldn't have a problem if you use the dataretrieval function as i show you. When data arrives are stored in a buffer and then given to you any
time you do the getdata function ( which then emptys the buffer only to
be filled with new data )
 
 
   
 

 computbill - 8/27/2007 11:38:16 PM
   
 Thanks, but I still have a problem. I'm looping thru requesting data on about 300 symbols. But the loop doesn't know when the data is received and parsed and stored. Some how I need to wait until the received data is stored before requesting more data. thanks in advance
 
 
   
 
 
 
 
Post Comment
You need to be a registered user to post a comment
 


Your Comment :

Your post may only
contain the [url],[img]
[quote] tags and smiles.

Syntax :
[url]address[/url]
[url=address]anchor[/url]
[img]address[/img]
[quote="nick"]text[/quote]

You are NOT logged in. You can Login or Register to phoenixbit.com


 
 

 
 


Tutorial Top Sites - The Best Free Tutorial Sites!



Tags : software, computer security , software developers , software programming , freeware programs , online games
.
 Copyright © 2007 PhoenixBit. All rights reserved
.