Server Socket Program sample in VB.net

By: Issac Emailed: 1645 times Printed: 2114 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The Server Socket Program is a VB.NET Console based Application. This program acts as a Server and listens to client’s request. We have to assign Port 8888 for the Server Socket, it is an instance of the VB.NET Class TcpListener, and call its start () method.

Dim serverSocket As New TcpListener (8888)
serverSocket.Start ()

Next we are creating an infinite loop for continuous communication to Client. When Server gets the request, it reads the data from NetworkStream and also writes the response to NetworkStream. For doing this create a new VB.NET Console Application Project and put the following source code into project.

Imports System.Net.Sockets
Imports System.Text
Module Module1
    Sub Main()
        Dim serverSocket As New TcpListener(8888)
        Dim requestCount As Integer
        Dim clientSocket As TcpClient
        serverSocket.Start()
        msg("Server Started")
        clientSocket = serverSocket.AcceptTcpClient()
        msg("Accept connection from client")
        requestCount = 0

        While (True)
            Try
                requestCount = requestCount + 1
                Dim networkStream As NetworkStream = _
                        clientSocket.GetStream()
                Dim bytesFrom(10024) As Byte
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
                Dim dataFromClient As String = _
                        System.Text.Encoding.ASCII.GetString(bytesFrom)
                dataFromClient = _
            dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
                msg("Data from client -  " + dataFromClient)
                Dim serverResponse As String = _
                    "Server response " + Convert.ToString(requestCount)
                Dim sendBytes As [Byte]() = _
                    Encoding.ASCII.GetBytes(serverResponse)
                networkStream.Write(sendBytes, 0, sendBytes.Length)
                networkStream.Flush()
                msg(serverResponse)
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End While


        clientSocket.Close()
        serverSocket.Stop()
        msg("exit")
        Console.ReadLine()
    End Sub

    Sub msg(ByVal mesg As String)
        mesg.Trim()
        Console.WriteLine(" >> " + mesg)
    End Sub
End Module

vb.net_server_socket_program.JPG

This server socket is in only a part of the socket program,we need a client to test it fully, we will see about it in detail in the client socket programming tutorial, you should first start the Server Socket Program and then start the Client Socket Program.

VB.net Home | All VB.net Tutorials | Latest VB.net Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(3)


1. View Comment

hi there, i was testing your code-samples,
but i keep getting errors on the server after the client disconected
is there any way to avoid this?
like to check if the client disconected and then quit the infinite loop, i tried checking the Connected attribute of the tcpClient but even though the client disconected it still "thinks" that it's connected though...that means, no success so far

can you give me a hand with this?


View Tutorial          By: Douglas at 2011-04-07 22:35:56
2. View Comment

I have error on "serversocket", vb.net highlights it everytime I am pasting the code to my project. here's the error statement :



Public Sub New(port As Integer)' is obsolete: 'This method has been deprecated. Please use TcpListener(IPAddress localaddr, int port)


View Tutorial          By: stephen at 2012-07-14 19:40:03
3. View Comment

Yes, you can use the newer one as follows
Dim tcpListener As New TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), portNumber)


View Tutorial          By: John at 2012-08-11 01:40:46

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Issac
Save/Write/Read image file from/to a database using Java program
How to modify the objects using java classes
Java program for Cloning
Java program for changeable wrapper class
A tutorial on Chat Server and Chat Client in VB.net
Chat Server in VB.net
Chat client in VB.net
How to open and read an XML file in VB.net
How to create an XML file in VB.net
XML and VB.net
How to create an XML file in VB.NET using Dataset
Multi Threaded Client Socket Programming in VB.net
Multi Threaded Server Socket Programming in VB.net
Multi threaded Socket Programming in VB.net
Client Socket Program sample in VB.net

More Tutorials in VB.net
Scope in VB.net
Unstructured Exception Handling in VB.net
Structured Exception Handling in VB.net
Creating Sub Procedures in VB.net
Creating Functions in VB.net
Passing a Variable Number of Arguments to Procedures in VB.net
Specifying Optional Arguments with default values in Procedures in VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Procedure Delegates in VB.net
Properties in VB.net
Understanding Scope in VB.net
Using Resume Next and Resume Line in VB.net
Using On Error GoTo 0 in VB.net
Getting an Exception's Number and Description in VB.net
Raising an Exception Intentionally in VB.net

More Latest News
Most Viewed Articles (in VB.net )
Create an Excel 2007 file in VB.NET 2005
Queue data structure in VB.net
How to use string chars (str.Chars() ) in VB.net
String Split function in VB.net
Passing a Variable Number of Arguments to Procedures in VB.net
Debug and Release Versions in .NET
Do Loop in VB.net
Insert Pictures in Excel 2007 from VB.NET 2005
Read Data from Excel using OLEDB in VB.NET 2005
How to export from DataGridView to excel using VB.net
Your first VB.NET Crystal Reports - A step by step guide
How to send email using VB.NET code
How to find IP Address of Host using .net code
Multi Threaded Server Socket Programming in VB.net
Throwing an Exception in VB.net
Most Emailed Articles (in VB.net)
Multi threaded Socket Programming in VB.net
Nested If and Single line if statement
Vb.net binary reader and writer
How to Open and Edit Cells in an Excel 2007 file in VB.NET
Format Excel 2007 Page in VB.NET
How to create an XML file in VB.net
Structured Exception Handling in VB.net
How To Connect To A MySql Database in VB.net
To read the entire worksheet in an Excel workbook through VB.net Code
Using Excel 2007 Chart in VB.NET 2005
How to send email using VB.NET code
How to find IP Address of Host using .net code
Chat client in VB.net
Properties in VB.net
“Using If with And” and Comparing two integers using If