Tutorial Winsock

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Tutorial For Winsock Control(Updated Now also Includes FAQ) by Keral.C.Patel.

Page 1 of 8

Hello Everybody, This Winsock Tutorial is


for anyone who has not heard of winsock or have never programmed
with winsock control. First of all I would like to tell you that
there are two type of protocols in winsock control through which
we can have a successful connection. They are TCP and UDP But
here we will only discuss TCP. UDP is also Great But generally
TCP Protocol is Used. Now Lets Start....

Designing
Part:-

First of all add winscok control to a


Standard exe project named 'Client'. Now Place that Winsock
Control on the form. It is invisible at runtime so its location
is not important. Place Two Text-Boxes named txtIP and txtSend
also place Command Buttons named cmdConnect and cmdSend on this
Form and in Last Place a List-Box control names 'lstMessages' on
the Form. Set Text-Boxes' Text property to "" and cmdConnect and
cmdSend's Caption Property to "Connect" and "OK" respectively.
Rename our Form to 'frmClient'. Set cmdSend's Default Property to
True. We will let the Default name for the Winsock Control as
this is the Winsock Tutorial.

Open another Standard exe project in another


window. All the Controls would be same as Client Project except
txtIP and cmdConnect they both are not needed here. Name this
Project as 'Server' and its Form as 'frmServer'.

Now the Coding Part


for the Client Project. Write the Following Code into Code
Window:-

Private Declare
Function SendMessage Lib
"user32" Alias "SendMessageA" (ByVal
hwnd As Long, ByVal wMsg As Long,
ByVal wParam As Long, lParam As
Any) As
Long

Private Declare
Function ReleaseCapture Lib
"user32" () As Long

Private Sub
cmdConnect_Click()

On Error Resume
Next

Winsock1.Connect txtIP.Text, "1412" 'Just remember this Port Number Should be Same on which
our Server is Listening

End Sub

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48418&lng... 29/4/2012
Tutorial For Winsock Control(Updated Now also Includes FAQ) by Keral.C.Patel. Page 2 of 8

Private Sub
cmdSend_Click()

On Error Resume
Next

Winsock1.SendData "Client:- " & txtSend.Text

lstMessages.AddItem "Client:- " &


txtSend.Text

txtSend.Text = ""

txtSend.SetFocus

End Sub

Private Sub
Form_MouseDown(Button As Integer,
Shift As Integer, X As Single, Y As
Single)

'For making the Form


Movable

ReleaseCapture

SendMessage Me.hwnd, &HA1, 2, 0&

End Sub

Private Sub
Label1_Click()

On Error Resume
Next

'Letting server know that


client has Disconnected.

Winsock1.SendData "Client is Disconnected!"

DoEvents

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48418&lng... 29/4/2012
Tutorial For Winsock Control(Updated Now also Includes FAQ) by Keral.C.Patel. Page 3 of 8

Unload Me

End Sub

Private Sub
Winsock1_DataArrival(ByVal
bytesTotal As Long)

On Error Resume
Next

Dim str As String

Winsock1.GetData str

lstMessages.AddItem str

End Sub

And The Following Code


into The Server project. It is Much Same as The Client Part
Except that we have to Set Winsock Control to listen on specific
Port on the Form's Load Event.

Private Declare
Function SendMessage Lib
"user32" Alias "SendMessageA" (ByVal
hwnd As Long, ByVal wMsg As Long,
ByVal wParam As Long, lParam As
Any) As
Long

Private Declare
Function ReleaseCapture Lib
"user32" () As Long

Private Sub
cmdSend_Click()

On Error Resume
Next

'This data will be sent to


the Client

Winsock1.SendData "Server:- " & txtSend.Text

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48418&lng... 29/4/2012
Tutorial For Winsock Control(Updated Now also Includes FAQ) by Keral.C.Patel. Page 4 of 8

lstMessages.AddItem "Server:- " &


txtSend.Text

txtSend.Text = ""

txtSend.SetFocus

End Sub

Private Sub
Form_Load()

On Error Resume
Next

'If one Copy of Our


Application is already running then don't load a new
one

If Not
App.PrevInstance = True Then

Winsock1.LocalPort = 1412 'This can be any Valid


Port Number

'Wait for Clients to


Connect with Your Server.

Winsock1.Listen

End If

End Sub

Private Sub Form_MouseDown(Button


As Integer, Shift As Integer, X As
Single, Y As Single)

'for making a form


Movable

ReleaseCapture

SendMessage Me.hwnd, &HA1, 2, 0&

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48418&lng... 29/4/2012
Tutorial For Winsock Control(Updated Now also Includes FAQ) by Keral.C.Patel. Page 5 of 8

End Sub

Private Sub
Label1_Click()

On Error Resume
Next

'So that it will not raise


an error after sending the data to the server which is already
disconnected

Winsock1.SendData "Server is Disconnected!"

'Here DoEvents gives time


to perform the winsock operation before unloading it from
memory

DoEvents

'Now Unload it

Unload Me

End Sub

Private Sub
Winsock1_ConnectionRequest(ByVal
requestID As Long)

On Error Resume
Next

'First Check if the Winsock


Control is Connected or not If connected then Close it

If Winsock1.State
<> sckClosed Then
Winsock1.Close

'Now accept the


Request

Winsock1.Accept requestID

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48418&lng... 29/4/2012
Tutorial For Winsock Control(Updated Now also Includes FAQ) by Keral.C.Patel. Page 6 of 8

End Sub

Private Sub
Winsock1_DataArrival(ByVal
bytesTotal As Long)

On Error Resume
Next

Dim str As String

'Now we will store data


that has came into this string

Winsock1.GetData str

'And Display that data in


the listbox

lstMessages.AddItem str

End Sub

That's It Bye Until Next


tutorial In which we will see about the ByteArrays() and UDP
Protocol. You can Download the Demo for Both of these Project to
Study it and Please Note that if You are testing it on a
Stand-alone Computer then Let the IP Address Be "127.0.0.1".
Yeah, You can change the Port Number but you will have to change
it in Both the Projects. They Both have to be Same for Winsock to
Communicate. This whole tutorial and
FAQ is also included in the zipfile. The samples included have
some extra code added to it. I will keep updating the FAQ's for
you people. If you have learned Something from this and want to
thank-me then

Please scroll down a


little and Vote for me.

Written By:- Keral.C.Patel.

Email:- keral82@keral.com

FAQ

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48418&lng... 29/4/2012
Tutorial For Winsock Control(Updated Now also Includes FAQ) by Keral.C.Patel. Page 7 of 8

Q. What is this TCP/IP I have heard a lot about


it?---(By Abhishek.Net)

A. TCP/IP refers to two network protocols (or


methods of data transport) used on the Internet. They are
Transmission Control Protocol and Internet Protocol,
respectively. These network protocols belong to a larger
collection of protocols, or a protocol suite. These are
collectively referred to as the TCP/IP suite. Protocols within
the TCP/IP suite work together to provide data transport on the
Internet. In other words, these protocols provide nearly all
services available to today's Net surfer. Some of those services
include Transmission of electronic mail, File transfers, Usenet
news delivery and Access to the World Wide Web. I think that most
platforms supports TCP/IP. Some of them are DOS, UNIX, Windows,
Macintosh and OS2.

Q. Why should I specify "127.0.0.1" as my IP for


testing this code on my PC?---(By
Vrutant7287)

A. This is also a detailed subject that why


should we specify "127.0.0.1" as our IP when testing something
locally. You can specify different IP and connect to that PC if
you have proper settings. E.g.:- You have a networked environment
and say there are three PC's, PC1, PC2 and PC3. You are on PC1
and you want to get connected with PC2 or PC3 then you can
specify the IP of PC2 or PC3 you will have a successful
connection only if there is another part of you application
running over there and You have set it up to listen for
connections on specific ports on that PC. For testing or running
the application locally (On standalone PC) you have to specify
"127.0.0.1" as IP. One More trick You can even specify the name
of your computer as IP. It will work.

Q. Why Specific Port and Please tell me more


about Ports.---(By SuperCoder77)

A. Here we will discuss this point with an


example. I think it will make it easier for everybody to
understand. Say For example on our server side there is an
application with a Winsock Control. In the Form Load or any
similar event we are initializing our server-side winsock control
to Listen on specific port by its Listen Method. If we don't
specify Port number then our application will get confused and it
will get data which is not meant for it. It can cause many
errors. That's why use specific port for data transactions. Ports
are the virtual gateways for communication with other objects. I
cannot cover all the things about ports over here It is out of
the scope of this tutorial.

Q. What is sckClosed?---(By
Jack)

A. It is a predefined Constant for the state of


the winsock control. If sckClosed is True then our Winsock Socket
is closed. And I would also like to explain about requestID. The
line after checking the state of our Winsock Control. In this
line of code Whenever a Client tries to connect with the Server
on the Port on which Server is listening then Server-side
Winsock's Connection Request event fires. Here we check about the

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48418&lng... 29/4/2012
Tutorial For Winsock Control(Updated Now also Includes FAQ) by Keral.C.Patel. Page 8 of 8

State of our control and fix it if necessary. Then we accept the


request from the client and thus a connection is established
between the Client and Server through which data can be
transferred.

Q. I wanted to know that will GetData Method get


whole string into the variable that has been passed to it as an
argument in the parameter?---(By Emily
Gratell)

A. Yeah. When Ever Winsock Control Gets any data


its Data Arrival event will fire. This is where we put our Code.
First we declare a variable and when we pass that variable in the
parameter of the GetData method of our Winsock Control it will
get all the data that was sent from the Other-side on that
specific Port.

Q. What are the uses of Winsock Control and If I


learn this will it benefit me?---(By Ronny
Ronson)

A. It is used in Client-Server environments. It


is used in the utilities for Banks and Hospitals and bigger
Corporations where there is a centralized server and all the
other Workstations are connected to it. Now It depends on you
that what benefit it will do. If you are thinking about making
Softwares for firms and banks and places where Client-Server
Interface is needed then you will surely benefit from this. This
Tutorial doesn't explains everything in detail but then also it
will get you started. I had read somewhere that whatever happens
to the Software market a programmer who knows how to implement
Client-Server Interface will never suffer.

Q. Can I make a torjan from this? Will it execute


whatever command I send to it?---(By
Arpan.Mehta)

A. I was not going to post this online but I am


getting many emails for this. Networking is a very powerful
technology and if its knowledge goes into wrong hands then, he or
she can create a havoc by using it for illegal purposes. I
personally don't recommend it. I don't believe in destruction I
believe in creation. My advice is to be creative. Now the answer
to this question is that you can surely make a trojan from it.
But be sure that where ever your trojan goes it will need VB
runtime Files if you make it in VB. This is just one idea, you
will get many bigger ideas as you go further in this subject of
TCP and networking and unleash its power.

Note from the


Author:- I am very pleased that people have came out
with questions. I am getting more and more questions everyday so
I thought that It would be better if I would provide a small FAQ
on this. If your question is not listed over here and you have
something different then please Email me at
keral82@keral.com I will try my best to answer your
questions. Regards. Keral.

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48418&lng... 29/4/2012

You might also like