Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Public Class NetReadWriteTestForm
Dim defaultRemoteIpAddress As IPAddress = IPAddress.Parse("169.254.11.150")
Dim defaultRemotePort As Integer = 10001
Dim remoteEndPoint As IPEndPoint
Dim clt As New TcpClient()
Dim stm As NetworkStream
Dim eot As Byte = &H4
Dim nl As Byte = &HA
Private Sub NetReadWriteTestForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RemoteIPBox.Text = defaultRemoteIpAddress.ToString
RemotePortBox.Text = defaultRemotePort.ToString
Me.Show()
End Sub
Private Sub ConnectButton_Click(sender As Object, e As EventArgs) Handles ConnectButton.Click
If Not clt.Connected Then ' Checkclient is not already connected.
clt = New TcpClient()
remoteEndPoint = New IPEndPoint(IPAddress.Parse(RemoteIPBox.Text), CInt(RemotePortBox.Text))
Try ' Open the client and stream.
clt.Connect(remoteEndPoint)
stm = clt.GetStream
Catch ex As Exception
MessageBox.Show("Client not connected or stream not opened.")
Return
End Try
If Not stm.CanRead And Not stm.CanWrite Then ' Check the stream can be read and written to.
MessageBox.Show("Could not read or write to the new stream")
stm.Close()
clt.Close()
Return
End If
stm.ReadTimeout = 1000
ConsoleBox.AppendText("Connected." + vbNewLine)
End If
ConnectButton.BackColor = Color.LimeGreen
End Sub
Private Sub DisconnectButton_Click(sender As Object, e As EventArgs) Handles DisconnectButton.Click
If clt.Connected Then ' Check client is already open.
Try ' Close client and stream.
stm.Close()
clt.Close()
Catch ex As Exception
MessageBox.Show("Client or stream not closed.")
Return
End Try
ConsoleBox.AppendText("Disconnected." + vbNewLine)
End If
ConnectButton.BackColor = SystemColors.Control
End Sub
Private Sub SendButton_Click(sender As Object, e As EventArgs) Handles SendButton.Click
Dim wBuf() As Byte = Encoding.ASCII.GetBytes(CommandBox.Text & Chr(eot) & Chr(nl))
Dim rBuf(1024) As Byte ' Expected ResponseLength not used yet.
If clt.Connected Then
If CommandBox.Text.Length = 0 Then
MessageBox.Show("Command box is empty." + vbNewLine + "Try Again.")
Return
End If
If clt.Connected Then ' Check client is connected.
ConsoleBox.AppendText("Data:" + Encoding.ASCII.GetString(wBuf) + vbNewLine)
Try ' Write data.
stm.Write(wBuf, 0, wBuf.Length)
Catch ex As Exception
MessageBox.Show("Could not write data.")
Return
End Try
End If
If ResponseLengthBox.TextLength > 0 Then
If CInt(ResponseLengthBox.Text) > 0 Then
ConsoleBox.AppendText("Reading..." + vbNewLine)
Try ' Read data.
stm.Read(rBuf, 0, rBuf.Length)
Catch ex As Exception
MessageBox.Show("Could not read response.")
End Try
ConsoleBox.AppendText(Encoding.ASCII.GetString(rBuf))
ConsoleBox.AppendText(vbNewLine)
End If
End If
Else
MessageBox.Show("Client is not connected yet.")
End If
End Sub
End Class