'Global declarations
Dim strRetPage As String = Nothing
Dim server As String = Nothing
'Creates the Socket for sending data over TCP.
Dim sock As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
server = txtServer.Text
Dim hostadd As System.Net.IPAddress = System.Net.Dns.Resolve(server).AddressList(0)
Dim EPhost As New System.Net.IPEndPoint(hostadd, 80)
Try
sock.Connect(EPhost)
Catch ex As Exception
MsgBox("Socket error: " & ex.ToString(), vbExclamation)
End Try
If Not sock.Connected Then
MsgBox("Socket error: " _
& Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()), vbExclamation)
Else
Me.Text = "Sockclient - Connected"
End If
End Sub
Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
Try
sock.Shutdown(SocketShutdown.Both)
Catch ex As Exception
MsgBox("Socket error: " & ex.ToString(), vbExclamation)
End Try
sock.Close()
If sock.Connected Then
MsgBox("Socket error: " _
& Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()), vbExclamation)
Else
Me.Text = "Sockclient - Disconnected"
End If
End Sub
Private Sub btnPopulate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPopulate.Click
Dim ASCII As System.Text.Encoding = System.Text.Encoding.ASCII
Dim StrGet As String = "GET / HTTP/1.1" & ControlChars.CrLf & _
"Host: " & server & ControlChars.CrLf & _
"Connection: Close" & ControlChars.CrLf & _
ControlChars.CrLf
Dim ByteGet As Byte() = ASCII.GetBytes(StrGet)
Dim RecvBytes(256) As Byte
Try
' Sends the GET text to the host
sock.Send(ByteGet, ByteGet.Length, 0)
Catch ex As Exception
MsgBox("Socket error: " & ex.ToString(), vbExclamation)
Return
End Try
' Receives the page, looping until all bytes are received
Dim bytes As Int32 = sock.Receive(RecvBytes, RecvBytes.Length, 0)
strRetPage = "Default HTML page on " & server & ":" & ControlChars.CrLf
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes)
While bytes > 0
bytes = sock.Receive(RecvBytes, RecvBytes.Length, 0)
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes)
End While
txtData.Text = strRetPage
End Sub