Here is a very simple (but working) class demonstrating how to use the basic features of the
TcpClient
class. Received byte stream is converted to an ASCII string, you can adapt it easily if you need a different string encoding (e.g. UTF8).
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class MyClient
'exported methods:
' public bool Connect(string server, int port)
' public bool IsConnected()
' public void Send(string msg)
' public string Read()
' public bool DataAvailable()
Public client As TcpClient
Private stream As NetworkStream
Private data As String
'constructor
Public Sub New()
data = ""
End Sub
Public Function Connect(server As String, port As Integer) As Boolean
Try
client = New TcpClient(server, port)
stream = client.GetStream()
Return True
Catch
Return False
End Try
End Function
Public Function IsConnected() As Boolean
If Not client.Connected Then
Return False
Else
Return (Not (client.Client.Poll(1, SelectMode.SelectRead) AndAlso (client.Available = 0)))
End If
End Function
Public Sub Send(msg As String)
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(msg)
stream.Write(bytes, 0, bytes.Length)
End Sub
Public Function Read() As String
GetData()
If data = "" Then
Return ""
Else
Dim s As String = data
data = ""
Return s
End If
End Function
Public Function DataAvailable() As Boolean
Return stream.DataAvailable AndAlso IsConnected()
End Function
Private Sub GetData()
If Not (client.Connected AndAlso stream.DataAvailable) Then
Return
End If
' Buffer for reading data
Dim bytes As Byte() = New [Byte](2047) {}
' Loop to receive all the data sent by the client.
Dim i As Integer
While client.Connected AndAlso stream.DataAvailable
i = stream.Read(bytes, 0, bytes.Length)
data += System.Text.Encoding.ASCII.GetString(bytes, 0, i)
End While
End Sub
End Class