Free Programming Tutorials & Source Code

 
  • Increase font size
  • Default font size
  • Decrease font size
Home Visual Basic.NET Socket Connect and Data Send in VB.NET

Socket Connect and Data Send in VB.NET

E-mail
(2 votes, average: 5.00 out of 5)
Function to connect to host machine, and send data via TCP Socket in VB.NET

First, add the following namespace
Imports System.Net
Imports System.Net.Sockets 

and the function:
    Sub SendData(ByVal data As String, ByVal port As Int32)
        Dim host As IPAddress = IPAddress.Parse("127.0.0.1")
        Dim ipendpoint As IPEndPoint = New IPEndPoint(host, port) ' Assign port and host
        ' Note: port should be listening. To check that, open DOS command, type netstat -an and press Enter.
        Dim socket As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Try
            socket.Connect(ipendpoint)

        Catch ex As Exception
            MsgBox(ex.Message)
            socket.Close()
            Return

        End Try
        Try
            socket.Send(Encoding.ASCII.GetBytes(data))

        Catch ex As Exception
            MsgBox(ex.Message)
            socket.Close()
            Return

        End Try
        socket.Close()
    End Sub

Happy coding!