Home »
VB.Net »
VB.Net Programs
VB.Net program to implement socket client
By Nidhi Last Updated : November 15, 2024
How to implement socket client in VB.Net?
Here, we will implement a socket client that will connect to the socket server according to the given IP address and port number. Then we can communicate to the server and send and receive data.
Program/Source Code:
The source code to implement the socket client is given below. The given program is compiled and executed successfully.
VB.Net code to implement socket client
'VB.Net program to implement the socket client.
Imports System.Text
Imports System.Net.Sockets
Imports System.IO
Module Module1
Sub Main()
Dim client As New TcpClient()
Dim Encoding As New ASCIIEncoding()
Dim strm As Stream
Dim sendStr As String = "Hello"
Dim recvLen As Integer = 0
Dim sendByteArray() As Byte
Dim recvByteArray(256) As Byte
Console.WriteLine("Connecting.....")
client.Connect("127.0.0.1", 15001)
Console.WriteLine("Connected to server")
strm = client.GetStream()
sendByteArray = Encoding.GetBytes(sendStr)
strm.Write(sendByteArray, 0, sendByteArray.Length)
Console.WriteLine("Data send...")
recvLen = strm.Read(recvByteArray, 0, 100)
For i = 0 To recvLen - 1 Step 1
Console.Write(Convert.ToChar(recvByteArray(i)))
Next
client.Close()
Console.WriteLine()
End Sub
End Module
Output
Connecting.....
Connected to server
Data send...
data received
Press any key to continue . . .
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 »