VB.Net program to implement socket server to accept client connections

Here, we are going to learn how to implement socket server to accept client connections in VB.Net?
Submitted by Nidhi, on January 18, 2021 [Last updated : March 08, 2023]

Socket server to accept client connections in VB.Net

Here, we will implement a socket server, which is used to accept connections from different socket clients and establish communication among them, and then we can send or receive data in a network.

Program/Source Code:

The source code to implement the socket server to accept client connections is given below. The given program is compiled and executed successfully.

VB.Net code to implement the socket server to accept client connections

'VB.Net program to implement socket server.

Imports System
Imports System.Text
Imports System.Net
Imports System.Net.Sockets

Module Module1
    Sub Main()
        Dim IP As String = "127.0.0.1"
        Dim PORT As Integer = 15001
        Dim len As Integer = 0

        Dim byteArray(256) As Byte
        Dim sendbytes(256) As Byte

        Dim Encoding As ASCIIEncoding
        Dim Skt As Socket

        Dim LocalHostIP As IPAddress = IPAddress.Parse(IP)
        Dim listner As New TcpListener(LocalHostIP, PORT)

        listner.Start()

        Console.WriteLine("Server is listening on port " & PORT)
        Console.WriteLine("Waiting for incoming connections..")

        Skt = listner.AcceptSocket()
        len = Skt.Receive(byteArray)

        Console.WriteLine("Received Data...")
        For i = 0 To len - 1 Step 1
            Console.Write(Convert.ToChar(byteArray(i)))
        Next

        Encoding = New ASCIIEncoding()
        sendbytes = Encoding.GetBytes("I have received data")
        Skt.Send(sendbytes)

        Console.WriteLine(vbCrLf & "Data sent to received client")

        Skt.Close()
        listner.Stop()
    End Sub
End Module

Output

Server is listening on port 15001
Waiting for incoming connections..
Received Data...
Hello
Data sent to received client
Press any key to continue . . .
implement socket server to accept client connections

Explanation

In the above program, we created a socket server on the localhost with a 15001 port. Here, the server is listening to accept client connections and receive data from the server and send data to the server. To test the program, here we used the most common network test utility (Hercules), then we connect to our server using Hercules and send data "Hello" using Hercules then our server program sends acknowledge data "I have received data" message to the Hercules tool.

VB.Net Socket Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.