Imports System
|
Imports System.Net
|
Imports System.Net.Sockets
|
Imports System.Threading
|
Imports System.Text
|
Imports System.IO
|
Public Class ClaseClienteTCP
|
#Region "VARIABLES"
|
Private Stm As Stream 'Utilizado para enviar datos al Servidor y recibir datos del mismo
|
Private m_IPDelHost As String 'Direccion del objeto de la clase Servidor
|
Private m_PuertoDelHost As String 'Puerto donde escucha el objeto de la clase Servidor
|
Private tcpThd As Thread 'Un handler a un clase thread para capturar los eventos de la clase
|
Private tcpClnt As TcpClient 'Variable de clase TcpClient
|
#End Region
|
|
#Region "EVENTOS"
|
Public Event ConexionTerminada()
|
'Public Event DatosRecibidos(ByVal datos As String)
|
Public Event DatosRecibidos(ByVal datos As Byte(), ByVal numbytes As Integer)
|
Public Event OnErrorDeConexion(ByVal ex As Exception)
|
#End Region
|
|
#Region "PROPIEDADES"
|
Public Property IPDelHost() As String
|
Get
|
IPDelHost = m_IPDelHost
|
End Get
|
Set(ByVal Value As String)
|
m_IPDelHost = Value
|
End Set
|
End Property
|
|
Public Property PuertoDelHost() As String
|
Get
|
PuertoDelHost = m_PuertoDelHost
|
End Get
|
Set(ByVal Value As String)
|
m_PuertoDelHost = Value
|
End Set
|
End Property
|
Public ReadOnly Property Conectado() As Boolean
|
Get
|
Conectado = tcpClnt.Connected
|
End Get
|
End Property
|
#End Region
|
|
#Region "METODOS"
|
Public Sub Conectar()
|
tcpClnt = New TcpClient()
|
'Me conecto al objeto de la clase Servidor,
|
' determinado por las propiedades IPDelHost y PuertoDelHost
|
Try
|
tcpClnt.Connect(IPDelHost, PuertoDelHost)
|
Stm = tcpClnt.GetStream()
|
'Creo e inicio un thread para que escuche los mensajes enviados por el Servidor
|
tcpThd = New Thread(AddressOf LeerSocket)
|
tcpThd.Start()
|
Catch ex As Exception
|
RaiseEvent OnErrorDeConexion(ex)
|
End Try
|
End Sub
|
Public Sub Desconectar()
|
tcpThd.Abort()
|
tcpClnt.Close()
|
End Sub
|
|
Public Sub EnviarDatos(ByVal Datos As String)
|
Dim BufferDeEscritura() As Byte
|
|
BufferDeEscritura = Encoding.ASCII.GetBytes(Datos)
|
|
If Not (Stm Is Nothing) Then
|
'Envio los datos al Servidor
|
Stm.Write(BufferDeEscritura, 0, BufferDeEscritura.Length)
|
End If
|
End Sub
|
#End Region
|
|
#Region "FUNCIONES PRIVADAS"
|
Private Sub LeerSocket()
|
Dim BufferDeLectura() As Byte
|
Dim BytesLeidos As Integer
|
While True
|
'Try
|
BufferDeLectura = New Byte(100) {}
|
'Me quedo esperando a que llegue algun mensaje
|
BytesLeidos = Stm.Read(BufferDeLectura, 0, BufferDeLectura.Length)
|
'Genero el evento DatosRecibidos, ya que se han recibido datos desde el Servidor
|
RaiseEvent DatosRecibidos(BufferDeLectura, BytesLeidos)
|
'Catch e As Exception
|
' Exit While
|
'End Try
|
End While
|
|
'Finalizo la conexion, por lo tanto genero el evento correspondiente
|
RaiseEvent ConexionTerminada()
|
End Sub
|
#End Region
|
|
End Class
|