20 marzo, 2012

Minimal tcp client code

' Minimal Tcp client for vb.net by abderramah (based in several msdn example codes)
'
' // este cliente no mantiene una conexión abierta, tan sólo conecta a una dirección, envía los datos indicados
' // y espera a recibir respuesta. En caso de no recibirla es posible que se quede en estado de espera, pero
' // con unas pocas líneas se puede solucionar.
'
' // petición http de ejemplo:
' // getsocket.socketsendreceive(192.168.2.5, 80, "GET / HTTP/1.1" + ControlChars.Cr + ControlChars.Lf )

Public Class GetSocket
Public Event errordebug(ByVal datae As String)

Public Function ConnectSocket(ByVal server As String, ByVal port As Integer) As Socket
Dim s As Socket = Nothing
Dim hostEntry As New IPHostEntry

' recibir información del host
Try
Dim ipe As IPAddress = New IPAddress(IPAddress.Parse(server).GetAddressBytes)
hostEntry.AddressList = {ipe}
Catch ex As Exception
Try
hostEntry = Dns.GetHostEntry(server)
Catch exa As Exception
hostEntry.AddressList = {IPAddress.Parse(server)}
End Try
End Try

' recorrer todas las direcciones del host (ipv4 e ipv6)
Dim address As IPAddress

For Each address In hostEntry.AddressList
Dim endPoint As New IPEndPoint(address, port)
Dim tempSocket As New Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)

Try
tempSocket.Connect(endPoint)
Catch ex As Exception
Return s
Exit Function
End Try

If tempSocket.Connected Then
s = tempSocket
Exit For
End If
Next address

Return s
End Function

' conectar, enviar petición y recibir la respuesta
Public Function SocketSendReceive(ByVal server As String, ByVal port As Integer, ByVal datae As String) As String
Dim ascii As Encoding = Encoding.ASCII
'httprequest= "GET / HTTP/1.1" + ControlChars.Cr + ControlChars.Lf + "Host: " + server + ControlChars.Cr + ControlChars.Lf + "Connection: Close" + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf
Dim request As String = datae
Dim bytesSent As [Byte]() = ascii.GetBytes(request)
Dim bytesReceived(128000) As [Byte]

' crear socket
Dim s As Socket = ConnectSocket(server, port)

If s Is Nothing Then
Return "Tcp connection failed"
Exit Function
End If
' enviar la petición tcp
s.Send(bytesSent, bytesSent.Length, 0)

Dim bytes As Int32
' leer los datos de entrada
Dim page As [String] = ""

' loop recibiendo
Do
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0)
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes)
Loop While bytes > 0
Return page
End Function
End Class
Publicar un comentario en la entrada