The Scripts Library Community

Socket Connect and Data Send in VB.NET

(1 vote, average: 5.00 out of 5)
  • Category: Visual Basic.NET Snippets
  • Friday, 24 July 2009 18:49
  • Written by Feras
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!
Comments
Add New Search RSS
Write comment
Name:
Email:
 
Website:
Title:
 
Please input the anti-spam code that you can read in the image.

!joomlacomment 4.0 Copyright (C) 2009 Compojoom.com . All rights reserved."