Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

FREE 12 month online training for ASP.NET & MS Expression Studio and a Free copy of MS Expression Web with Windows Server Purchase
Socket Programming using Visual Basic.Net

Author: Faraz

This article will shows you, how to create a client and a server application that communicates using sockets. This article also contains the sample program. Read on to learn more!

The classes and enumerations in the System.Net.Sockets namespace provide an implementation of the popular Windows Sockets (Winsock) interface for use with .Net languages.

 

The original sockets were developed as part of the UNIX operating system, and they have been widely used as a simple way to pass data between programs. They are widely used on the internet and can be used between programs on a single machine as well.

 

Sockets are similar to telephone communications between people working for different companies. If I’m going to contact you from my phone, I need to know you company phone number and your extension. In socket communication, the “Phone number” is the IP address of the machine you want to talk to. You may know you want to talk to. You may know this as a dotted IP address of the form 127.0.0.1 or as a more humanly friendly representation of www.domainname.domaintype

 

Just as everyone in an office has an extension on the same phone number, every program on a machine that wants to use sockets uses a unique port number. Port number ranges from zero upwards: The reserved port number ranges from 0 to 1024. These reserved ports are used for official purposes or by Web servers and mail servers. You are free to use port numbers above 1024 for your own use.

 

A server process can reserve a port number and then sit on it waiting for incoming calls. A client process makes a call by opening a socket and specifying the IP address and port number it wants to connect to. If the address and port number are correct, the two process will be connected.

 

How the sockets can be used?

 

After the whole discussion about the sockets, the question arises in our mind that how we can use sockets. Now the answer is, System.Net.Sockets namespace contains a Socket class that will do everything you want, Microsoft recommends that you use the two classes that it supplies to represent either end of a socket connection. TCPClient represents the client end, whereas TCPListener represent the server end.

 

At the client end, you create a TCPClient, passing it the IP address of the machine you want to connect to and the port that the server process is using.

 

When the connection has been established, the GetStream() method returns a reference to a Stream object, which is used to read and write through the sockets:

 

       Dim readStream As Stream = serverListener.GetStream

 

The Stream’s Read() and Write() methods can be used to pass data through the socket, but because they use bytes, it is necessary to convert character data into bytes before sending. As an alternative, you can use the Send() and Receive() methods that TCPClient inherits from socket, which also work with byte arrays.

 

TCPListener implements a parallel set of functionality that helps implement the server side of a socket connection. A TCPListener is created to listen on particular socket, which obviously has to match the ones that clients will be calling in on:

 

        Dim clientListener As New TcpListener(8585)

 

 

Once created, the Start() method starts the object listening for network connections. There are two ways in which a listener can connect to incoming clients. One way is to call AcceptSocket() or AcceptTCPClient(), both of which will block until a client connects. Alternatively, the server can periodically call the TCPListener’s Pending() method, which returns true if any clients are waiting to connect. If there are clients waiting, calls to AcceptSocket() or AcceptTCPClient() will connect immediately.

 

Calls to AcceptSocket() or AcceptTCPClient() returns a Socket reference, so the server code can use the Send() and Receive() methods to pass data through the connection. Once the conversation is finished, the Stop() method stops the TCPListener from listing for network traffic.

 

After the discussion about the Socket class and the methods that are involve in communication we now turn our concentration towards the application making.  Use the following steps to create a client and server application:

 

  1. Create a  console application for client and place the following code:

Imports System.IO

Imports System.Net.Sockets

 

Module Module1

 

    Sub Main()

 

        Try

            Console.WriteLine("Connecting to 8585 Local Host")

            Dim serverListener As New TcpClient("localhost", 8585)

            Dim readStream As Stream = serverListener.GetStream

            serverListener.SendBufferSize = 256

 

            Console.WriteLine("Input Lines:")

            Dim str As String = Console.ReadLine()

 

            While True

                Dim sendBuff As Byte() = System.Text.Encoding.ASCII.GetBytes(str)

 

                readStream.Write(sendBuff, 0, sendBuff.Length)

 

                If str.StartsWith(".") Then

                    GoTo Done

                End If

 

                str = Console.ReadLine()

            End While

 

Done:       Console.WriteLine("Done")

 

        Catch exp As Exception

 

            Console.WriteLine("Exception: " + exp.ToString())

 

        End Try

 

 

    End Sub

 

End Module

 

 

 

  1. Select the New console application option from the startup page and place the following code for server:

Imports System.IO

Imports System.Net.Sockets

 

Module Module1

 

    Sub Main()

        Console.WriteLine("")

        Dim clientListener As New TcpListener(8585)

 

        clientListener.Start()

 

        Console.WriteLine("")

        Dim mySocket As Socket = clientListener.AcceptSocket()

 

        Console.WriteLine("")

 

        Dim recieveBuff(225) As Byte

        mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)

        Dim str As String = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))

 

        While Not str.StartsWith(".")

            Console.WriteLine(str)

 

            mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)

            str = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))

 

        End While

 

        Console.WriteLine("")

        clientListener.Stop()

 

    End Sub

 

End Module

 

 

 

 

  1. Run the both application either on the same machine or on a different machine without any trouble, providing that TCP/IP networking is installed correctly.

 

  1. The converted and trimmed line is printed out, and then the code loops around, reading and displaying lines until a line appears that start with a “.”. At this point, the Stop() call tells the socket to stop listening for network traffic, and the program terminates.

 

Note:  First run server and then the client application.

 

 

 

Summary:

·        Create a console application in visual basic.net for socket client.

·        Create a console application in visual basic.net for socket server.

·        Connect the server and client on the selected port and using GetStream() method read and write messages. The program will terminate on “.”. Means Stop() method executes when it reads the “.” at the start of the line.

Article Comments
Please send me this article.

Posted on 5/16/2006 5:37:00 AM by qasim umer

Hi
Thanks Its nice help to learn socket programming for bigginers
thanks n Reagards
Yuvraj Patil

Posted on 11/28/2006 6:07:48 AM by yuvraj

Hi
Thank you.but it is smal for learninig socket program with vb.net.I want an ebook this Please

Posted on 2/18/2007 2:14:53 AM by Abolfazl

Hi

This good for begining .....
thanks alot
it' willy help full

Posted on 7/12/2007 4:08:24 AM by rix

This actually does works, Thank you

Posted on 12/23/2007 8:48:13 PM by bill

hi,
nice code . I am beginner so i think it is quite helpful for me.and send me ebook or other article if you have

thanks again

Posted on 1/4/2008 11:05:34 AM by Diwaker

Im a little confused by this tutorials.
One, when I paste the code in, it compiles fine, but it doesnt do anything (thats with the server and client both running) Secondly, if I put Main () on the form load, I get a message from my firewall asking me to unblock, which I do, then nothing. I compiled both of them, and ran, but my server end of it doesnt even show up on my screen. Im a little confused

Posted on 1/8/2008 3:06:46 AM by Shaun

Hey i am studying your article , i think this is good for net progrming

thanks

Posted on 1/22/2008 1:25:35 AM by Ramesh

it lucks good. even also working good..
but i have some issues abt this programme..when ..i closed client and restart the it...client loose the connection with server...so describe about management of connection and accept socket..whn we are goin to restart both or any one..

thanks

Posted on 1/29/2008 4:02:24 AM by dilip virani

It is a great piece. pls send a copy of the article and more tutorials on socket programming. thanks. God bless.

Posted on 2/13/2008 2:35:04 AM by adesola williams

could you tell me how i can send pictuer from picbox.image by socket in vb.net ?

Posted on 2/22/2008 4:12:28 AM by massoud

socket programming under vb.net

Posted on 2/26/2008 9:06:58 PM by Honeal Reid

they give only suitable solution what needed for it

Posted on 3/1/2008 1:43:47 AM by chating contol and code in vb.net

hi
chating process code in vb.net if use socket then how it be.like that what controls are use code where

Posted on 3/1/2008 1:48:18 AM by kirti

danke. this is help me to learn sockets vary quickly the tutorial. much thank you to faraz!!

Posted on 3/11/2008 2:42:59 AM by aaron

Cool This is nice work i will try to do with
windows application and if any one have any code about Socket
Thanks

Posted on 4/17/2008 9:30:37 PM by Scarface

can u give me code for C# Windows Application Socket programming
.

Posted on 4/20/2008 11:27:03 AM by newaz

can u give me code for C# Windows froms Application Socket programming .

i deed, i want to do that in Visual C# 2008, because i am asked to do that.

so, i dont have any option.

Anyway, i am really grateful for your cordial cooperation.

thanks

Posted on 4/23/2008 10:52:48 PM by newaz

pls send more tutorials on socket programming using c.

Posted on 7/9/2008 3:33:52 AM by sarif

pls send socket programming under vb.net,asp.net,c#.net
and can u give me code for vb.net ,asp.net,C# Windows Application Socket programming

Posted on 7/14/2008 3:16:57 AM by bala

thanks for providing the code, the thing is that this is for console application. but i want to connect my ASP.net mobile page using VB scripting to the server usind VB.NET, can anybody please help me...

Posted on 9/19/2008 3:42:30 AM by Omer Bin Masroor

nice one! works great.
simple but effective

Posted on 9/24/2008 10:03:08 PM by brady

Good one to learn Socket Programming
Thanks for the post.

Posted on 10/31/2008 1:29:21 AM by Jamshid

I have problem on the server side in this line:
Dim clientListener As New TcpListener(8585)

its shows a warning message: "'Public Sub New(port As Integer)' is obsolete: 'This method has been deprecated. Please use TcpListener(IPAddress localaddr, int port) instead. http://go.microsoft.com/fwlink/?linkid=14202' "

and when i ran the server code it shows the window trying to listen to the port, but it gives some kind of exception that i couldnt read coz it closes fast.

what to do?

am using VB 2005

thanx

Posted on 11/10/2008 12:42:03 AM by mazen itani

@mazen itani
Change:
Dim clientListener As New TcpListener(8585)
To
Dim clientListener As New TcpListener(Net.IPAddress.Parse("127.0.0.1"),8585)

Posted on 11/25/2008 8:27:12 AM by DK

Nice! Its a very good article for the starters

I am get some problems in checking the state of the socket connection.

Please help.

Posted on 11/28/2008 10:59:04 PM by Afzal

its a good tutorial..Thank u .. =)

Posted on 11/3/2009 1:42:01 AM by lim

really nice & helpful article.

Posted on 12/11/2009 4:59:21 AM by sushma

Nice Tutorial for Begineers. Thanks a Lot.........

Posted on 12/14/2009 2:40:48 AM by Ram

I am really happy to see this very useful article at first on my search.

Posted on 2/3/2010 10:45:47 AM by Vaduganathan

First Of All "Thank You" for your Details Code Snippet
it is very very very helpfull for beginner

Posted on 3/6/2010 2:17:25 AM by Golla Sravan Kumar

It is very helpful...

Can any 1 post windows application for multiple clients in vb .net

Posted on 3/6/2010 11:46:12 PM by Nityam

thanks for this article

Posted on 3/23/2010 10:47:03 PM by ronadi

Thanks!

Posted on 3/25/2010 4:55:32 AM by Anuj

Nice Code ... :)

Posted on 4/13/2010 8:51:45 AM by Sash

fantastic

Posted on 5/12/2010 1:15:32 PM by jeet shah

hi plz send for me about network programming
tanks

Posted on 5/12/2010 11:28:46 PM by amir

really its good for anyone who teach vb.net.

Posted on 5/13/2010 12:12:37 AM by tt

This is good, please how do I implement this is I want text from a box to be sent?

Posted on 6/18/2010 2:04:25 AM by Lawal

A good example for core concepts. Thanks

Posted on 6/20/2010 3:19:41 AM by Haji Naveed Akthar

thanks
this is good article for starting socket programming but please send me ebook for detail studying

Posted on 6/24/2010 1:12:28 AM by deepak hakare

plz send me the files of this application

Posted on 7/14/2010 2:35:00 AM by Sarosh

Clear & easy to understend sockets. Thx

Posted on 7/15/2010 3:17:17 PM by MAC

I have used this article for incrementing my knowledge.
I want some extra information about vb.net
If you have any type of this information then,
please sent to me on vishayash@rediffmail.com

Posted on 7/17/2010 2:04:50 AM by vishayash

hi its verry informative....
i want to make it for a website... is it work for that...???
pls give me the suggestions...

thanks & regards...

Posted on 9/30/2010 1:27:36 AM by sanjay

Nice Article

Posted on 12/1/2010 11:13:17 PM by Kamran

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< Using ADO.Net Transaction in Visual Basic.Net

Disclaimer - Privacy
© 2002-2014 DevASP.net