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 |
|
|
|
| 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 
|
| Tutorial Description : | This is the part 2 of the winsock tutorial for visual basic 6. In this part i will show you not just how to connect a client with a server, but how to create a multiple connection receiving server, and how to make a real chat network , something like IRC |
| | | Who should read this : | This tutorial targets the beginners in Visual Basic 6. This is part 2 so if you know nothing about winsock then you must first read the part 1 Although i will try to explain everything asthoroughly as i can, basic knowledge of visual basic 6 or generallyprogramming 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 multi user 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, but this server can receive more than one clients and create a simple chat channel |
| | | 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 , and this is what I am going to show you in this tutorial |
|
| | | | Download the Tutorials Example Source Code 
|
| | | | Writting the Client | | | The client is actually the exact same used in part 1 , since changes have been made (changed a bit one line ) you can read how to write it at part 1,Here is the Link
| Writting the Server | | | The server in we want to create is much more complex than part 1, since this one will be able to handle multiple client , and be responsible to distribute data to clients.
If you don't know how to create the simple server i suggest you read Part 1 first. | | | Ok, Here is the Server Form | 
| | Now before i get into it , i must first tell you some basic things about control arrays. Control arrays is a very nice feature of VB that allows you to have many controls and handle them just like you would use an array. Control can be anything ( labels, command buttons, picture boxes , winsock , etc) and you can create new controls at runtime, unload them , or use them by saying ControlName(ControlIndex) where ControlName is then name of your control eg. label1 , pic1 and so on , and ContolIndex is a number which represent the current control in the control array
I made a simple control demonstration program to see and test how to use them You can download it from here
Note : To create a control array, select a control , for instance a label , and copy it , then try to paste it back to the form. Visual Basic will then ask you "You already have a control named 'xxxxxx'. Do you want to create a control array?" and click yes |
| Ok now back to the winsock thing...
The logic behind this is to create a server that will be listening on a port. When a connection is requested by a client , instead of assigning the connection to the listening socket , a new socket will be created , and the connection will be assigned to it , thus keeping the listening socket listening for requests to come... | | In the project we will have a global variable SocketCounter that will count how many sockets we made and what will be the index of the new one... That isn't really necessary because you can always get control count using the controls array .count function ( see the control array example above ) | | | | | | First the listening button code.... | | | Private Sub bntListen_Click()
On Error Resume Next 'close and unload all previous sockets For n = 1 To SocketCounter sock1(n).Close Unload sock1(n) Next
On Error GoTo t
'sock1(0) is the name of our Winsock ActiveX Control
sock1(0).Close 'we close it in case it listening before
'txtPort is the textbox holding the Port number sock1(0).LocalPort = txtPort'set the port we want to listen to '( the client will connect on this port too)
sock1(0).Listen'Start Listening
txtLog = "Listening on Port " & txtPort
Exit Sub t: MsgBox "Error : " & Err.Description, vbCritical End Sub |
| | |
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 ) But remember, we must create a NEW winsock control and assign the connection to it, otherwise it you assign the connection to the sock with index 0 (which is our listening sock ) then it will stop listening for connection so clients will not be able to connect to the server
Bellow is the code that handles the connection request | | | Private Sub sock1_ConnectionRequest(Index As Integer, ByVal requestID As Long) 'txtLog is the textbox used as our log.
'this event is triggered when a client try to connect on our host 'we must accept the request for the connection to be completed, 'but we will create a new control and assign it to that, so 'sock1(0) will still be listening for connection but 'sock1(SocketCounter) , our new sock , will handle the current 'request and the general connection with the client
'increase counter SocketCounter = SocketCounter + 1
'this will create a new control with index equal to SocketCounter Load sock1(SocketCounter)
'with this we accept the connection and we are now connected to 'the client and we can start sending/receiving data sock1(SocketCounter).Accept requestID
'add to the log txtLog = "Client Connected. IP : " & sock1(0).RemoteHostIP & " , Client Nick : Client" & sockcounter & vbCrLf
'tell our client his assigned nickname sock1(SocketCounter).SendData "Your Nick is ""Client" & SocketCounter & """"
End Sub |
|
| Next we need to write the DataArrival event. What is important to remember for this, is that when a client send a text string to the server , it is not meant for the server, but all other clients that are currently connected. ( remember we are trying to create an IRC like chatroom ) So when server get some data from the client , it need to redistribute it to all connected clients (also informing them who send the text ) | Ok here is the code for the dataarrival event | | | Private Sub sock1_DataArrival(IndexAs Integer, ByVal bytesTotalAs 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(Index).GetData dat, vbString 'writes the new data in our string dat ( string format )
'add the new message to our chat buffer txtLog = txtLog & "Client" & Index & " : " & dat & vbCrLf
'now the client says something, wich arrived at the server... 'the server must now redistibute this message to all other connected 'clients... On Error Resume Next 'Error Handler For n = 1To SocketCounter IfNot n = Index Then 'we don't want to send the msg back to the sender :) If sock1(n).State = sckConnected Then 'if socket is connected sock1(n).SendData "Client" & Index & " : " & dat End If End If Next
End Sub |
| | | | | Ok! those are the most crucial parts, there is also theError and Close events but there is nothing special about them, you can see them in the example source | |
|
Download the Tutorials Example Source Code 
| | |
| | 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 | | |
|
|