Updated Version Of Winsock Tutorial. For beginners who want to learn about Winsock Control and Networking. A must read for someone who want to Implement a Client-Server Interface.
Terms of Agreement:
By using this article, you agree to the following terms...
You may use
this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
You may link to this article from another website, but ONLY if it is not wrapped in a frame.
You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
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
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
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
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&
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
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
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
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.
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come
out every day, so no prevention program can catch 100% of them. For your own safety, please:
Re-scan downloaded files using your personal virus checker before using it.
NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
Scan the source code with Minnow's Project Scanner
If you don't have a virus scanner, you can get one at many places on the net
including:McAfee.com
Terms of Agreement:
By using this article, you agree to the following terms...
You may use
this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
You may link to this article from another website, but ONLY if it is not wrapped in a frame.
You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
Good to start with, dosent really explain alot though. certainly not Intermediate code. but still if it helps someone then it has served some purpose which is the whole point (If this comment was disrespectful, please report it.)
Okay people I will not say any bad word to anyone. Write what ever you want ot write. I also have supporters here. They like this tutorial. (If this comment was disrespectful, please report it.)
Very great tutorial for beginner or advanced users of vb , actually some poeple know coding but not all are good and have more experiences in winsock , for example me iam not that much good in it, but this tutorial teach me a lot :) keep coding thats great from you ! Thx mate !!!! (If this comment was disrespectful, please report it.)
I know hard-disk can fail to work properly but processor busrting you must be god. ...keep in mind guys ---WORLD PEACE--- (If this comment was disrespectful, please report it.)
Its more beginners code. I heard some bad things on that control from some hat created a replacement control for ms winsock control using advanced api's. Though, nice commented. (If this comment was disrespectful, please report it.)
by posting silly comments you are just disappointing the coder, and i think these comments are getting over the limits like google search etc. Good Code! (If this comment was disrespectful, please report it.)
Dude! This tutorial Kicks! It Is The Best Tutorial I Have Seen In.... FOREVER On Winsock! Keep In Touch Buddy! Peace Out! (If this comment was disrespectful, please report it.)
Did you know that when your US of A attacked Afghanistan, there was An American fighting for the talibans. And "That puts all Americans to shame" that a citizen wants to destroy his own country(pretty shameful act). please keep your racial comments upto you. not all people are same, and who are you to decide or comments on his personal profile, is alt.com your site?, your own it or what.? (If this comment was disrespectful, please report it.)
Ha! you did it again. Why do you keep on removing any negative comment? OK, now it's scripted and I will let it go for a couple of weeks. By the way If you want to tell me something, forget it, everything gets filtered out. This is now going on for a couple of days. 'Mister' Patel is trying to get votes verry aggresively. This includes spamming PSC users asking for votes, removing negative comments, sending emails with abusive comments if you do have anything negative to say. And I even suspect that he uses dummy account to vote for himself and putting in possitive remarks. For this last I do not have rock sollid prove, but I think it's a verry big coincidence that the same people voted exelent for his other submition (see 48395)Here are also some of the abusive emails that I received from Patel: (If this comment was disrespectful, please report it.)
I would not have been so persistent if it was only the spam request for a vote. It was only after patel being so abusive that I decided to post whatever is now here. See what he wrote after I gave him 4 globes! Of course that made me change it to only 1 globe. Patel has been verry abusive and manipulative. He keeps on removing almost every negative comment. I am not debating the quality of the code here. That's all up to the voters. It's Patel's behaviour that bothers me. I think that compared to what Patel wrote I'm verry kind. (If this comment was disrespectful, please report it.)
(1) Patel wrote to me : Hello There Buddy, This is Keral. I have posted an Article on PSC and I would like you to take a look at it. If you like it then Please Vote for it as a Friend of mine It will Help me a Lot. Thanks. The Link is:- ............. (If this comment was disrespectful, please report it.)
(2) Patel wrote to me : Just keep on posting comments buddy and I will keep on deletting. As I am a HardWorker and You cannot stop me from deleting it. Thanks anyway for your vote. It degraded my average but then also it was a Vote. Lets have a war baby. (If this comment was disrespectful, please report it.)
(4) Patel wrote to me : Baby I was not spamming your mail box the first time but now You see what I will Do if you Keep doing this kind of things with me. I am not afraid of people like you. Not because this is internet I will do anything to take a revenge for this. Just remember I also have Mail-Bots which will fill this inbox of Yours If I wish. I know that spamming is illegal but I was just marketing. Still I am telling you that I was just marketing. My intention was not to spam your mail-box. Anyway If you would have seen that tutorial then you would have learned something from it. I gave you some knowledge in free and You are doing all this things to me. OK god is watching. I don't want to say anything more. bye and have a Great Day. Your Friend, Keral (If this comment was disrespectful, please report it.)
(5) Patel wrote to me : Okay Baby Now I had explained you then also you did'nt understood. Get ready for a ride. I am going to do something very bad and it will hurt you much more then all that spam I had sent to you. Remember If in next 10 or 15 days your hard-disk fails or your processor bursts out then let me know So that i can know that It really worked or not. Thanks. (If this comment was disrespectful, please report it.)
Now Edwin Stop this or Else this whole programming community will be against you. ---STOP THIS--- If I see any of this things over here again then Patel will not do anything. But I will start posting much more bad comments on your page. We don't want a war over here. Americans are known for their peace loving nature. So not only Indians but Americans will also Oppose this. (If this comment was disrespectful, please report it.)
OKAY This is what EDWIN wrote to me. He is a spammer I think so. Patel only emailed us and we got something in return but this EDWIN says me to think once more on my vote. I liked this tutorial and I voted what I thought was good. My decisions are un-changeable. I am a man of my word. So guys here I present the email which EDWIN spammed in my inbox just take a look at it and decide that what kind of person he is. (If this comment was disrespectful, please report it.)
About your vote on PSC submition from Karal.C.Patel http://www.planet-source-code.com/vb/scripts/showcode.asp?txtCodeId=48418&lngWId=1I have monitored this submition for some time and I have seen dozen of comments on his post that got deleted by the author. It even got so far that I decided to create a script that enforse my posts to stay there. So I would like to ask you to read these comments. If you do so you might reconsider your vote. I do not mean that it's bad code, but someone who is using this kind of methods to get votes should not be on PSC. Sorry for disturbing you about this and that I had to use the same method as Pathel. Keep the planet clean, Regards, Edwin Vermeer
(If this comment was disrespectful, please report it.)
I would say: remove every post from 9/17/2003 3:00:30 AM and later. Then you all shut up and grow up. (If this comment was disrespectful, please report it.)
I agree with Jonas. The votes are showing that there is something wrong here, but who cares what or who or how. Just clean this up. (If this comment was disrespectful, please report it.)
Patel, you can stop sending those insulting, semi-coherent emails because I voted poor. Let me make this clear - I think your code is below average in the intermediate category. Look at this realistically, your demonstration of using a winsock control is a basic subject and not very well written. The fact that you have no qualms harassing people via email didn't affect your score, I was just obliging your request to vote on it. (If this comment was disrespectful, please report it.)
Patel wrote to me: "Thanks Buddy For Showing your guts. I know you liked it but then also You wanted to give me 1 because I specially invited you. You all people don't like to be invited I think so. Because you are animals and only humans like to be invited you all are nomadics no where to go and If you people go there you spread sh*t over there." (If this comment was disrespectful, please report it.)
Hello Everybody, I am really sorry for my behaviour in the last week. I specially apologize to Edwin Veermer and John Williamson and Sebastiano Pallaro. So please forgive me like a great man does. I will be very kind of you people. And all of those people who recieved my mail and they think that it was not right then sorry to all of you. (If this comment was disrespectful, please report it.)
Thanks Keral, I will put back my original vote. I guess we all went a little overboard. Very good of you to apologies first. Well herewith I would also like to apology for my behavior. I'm especially sorry that it bothered other PSC users. I hope we can continue to use PSC the way it should. Keep the planet clean. Regards, Edwin (If this comment was disrespectful, please report it.)
Keral, as I told you via email- an apology to get some people off your back doesn't change anything. You already apologized to me via email and promised to stop deleting negative comments yet continued to do it, so why should I think this "apology" is any different than the previous one you didn't honor? You have already demonstrated that you will do anything to try to win this contest whether it be spamming for votes, harassing people who voted poor, and give insincere apologies in a pathetic attempt to save face. The bottom line is this - you are willing to offer a token apology as damage control, but you sure aren't willing to give up the votes that your unscrupulous behavior has generated. (If this comment was disrespectful, please report it.)
If you are successful with these kinds of actions, what is to stop you or anyone else from continuing to follow this formula of success in trying to manipulate PSC? I don't think spamming/harassing other PSC users should be tolerated, and this is a dangerous precedent that Ian needs to address. If your code wins the COTM contest it should be SOLELY on the quality of the code and not because you have conducted a campaign to drive traffic to it using spam, deception, and harassment of fellow PSC users. (If this comment was disrespectful, please report it.)
Truly, well thought-out, nicely erected article. This piece of construction Deserves a 1.......n globe. 5 globes from my part. (If this comment was disrespectful, please report it.)
This Tutorial deserves a 1......n Admiration. Well planned, well thought out, nicely erected construction. 5 globes from my part. (If this comment was disrespectful, please report it.)
Thanks PSC Users, Thanks very much for your kind Comments and your Precious votes. ----From the Author of this Tutorial. (If this comment was disrespectful, please report it.)
hey there, nice work i must admit, explained some things i didn't knew about..., keep it on, greetz (If this comment was disrespectful, please report it.)
Okay This is my last comment for this month. Thanks to all PSC users for your kind comments and also thanks to all of those who kept me awake for this 20 nights. Bye. (If this comment was disrespectful, please report it.)
3/13/2004 12:19:09 AM:
I think everyone should just relaxe, if he is that desperate to win the contest, let him do so.
VB.NET > VB6.0 (If this comment was disrespectful, please report it.)
3/13/2004 12:20:47 AM:
just relaxe and let the guy be desperate to win the contest.
VB.NET > VB6.0 (If this comment was disrespectful, please report it.)
Yep great code, It's something you could probably pick up elsewhere on the internet, but not half as well formed as this one..
5 stars from me! the apperance is just great (If this comment was disrespectful, please report it.)
3/27/2004 9:27:54 AM:
I am learning about Winsock, want to learn much more. This is a start in any case, but people please grow up. (If this comment was disrespectful, please report it.)
http://asd1060.tripod.com (If this comment was disrespectful, please report it.)
7/15/2004 5:52:14 PM:
I also like the tutorial it helped me a bit, but I think you deserve a 5*****... I think this and other tutorials can get me up to my feet. Thanks again ;) (If this comment was disrespectful, please report it.)
11/25/2004 7:22:37 AM:
Good tutorial, I, personally, would put it in the beginners section, but nevermind. It still taught me the basics. (If this comment was disrespectful, please report it.)
1/22/2005 2:25:55 AM:
Very nice I like it!!! its another stepin stone for thank you. (If this comment was disrespectful, please report it.)
2/1/2005 2:24:54 PM:
I was just wondering why this gives error...Private Declare Function SendMessage Lib (If this comment was disrespectful, please report it.)
3/10/2005 6:03:17 AM:
Great Tutorial. Very Easy to understand and learn. keep on writing the tutorials! (If this comment was disrespectful, please report it.)
For some reasong when I add the winsock control in vb.net and I try to add it on the form..i get error (If this comment was disrespectful, please report it.)
7/1/2005 5:23:26 AM:
highly understandable An Excellent article (If this comment was disrespectful, please report it.)
Ok, hope no one thinks this comment is abusive, because it dont mean to be. Its in the intermediate category, yet winsock is childs play and you say in the descrption that its for beginners. Very poor layout of your tutorial, code is somewhat sloppy, port is set as a string, should be integer. Why is it that only the asian people are giving positive comments and votes? I also noticed the same people are voting on your other submissions, maybe its favoritism, or maybe you have multiple accounts. I voted poor simply because it dont demonstrate how anything works, its in the wrong category level and is simply sloppy code. avisonjohn@yahoo.co.uk (If this comment was disrespectful, please report it.)
Add Your Feedback
Your feedback will be posted below and an email sent to
the author. Please remember that the author was kind enough to
share this with you, so any criticisms must be stated politely, or they
will be deleted. (For feedback not related to this particular article, please
click here instead.)