elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recuerda que debes registrarte en el foro para poder participar (preguntar y responder)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Problema con Modulo de clase
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Problema con Modulo de clase  (Leído 1,475 veces)
_katze_

Desconectado Desconectado

Mensajes: 140



Ver Perfil WWW
Problema con Modulo de clase
« en: 10 Octubre 2011, 01:36 am »

Hola a todos amigos ! les cuento e creado esa clase (son dos), para el uso de socket, pero tengo un problema cuando voy a hacer uso de los eventos ! al mostrarlos me aparecen como privados y me da error en listview y demas cosas, que podra ser ? o estoy haciendo algo mal?

Código
  1. Imports System.Text
  2. Imports System.IO
  3. Imports System.Net
  4. Imports System.Net.Sockets
  5. Namespace Network
  6.    Public Class Cliente
  7.        Implements IDisposable
  8. #Region " Declaraciones "
  9.        Private Socket As Socket
  10.        Private CallBackHandler As AsyncCallback
  11.        Private ClientList As ArrayList = ArrayList.Synchronized(New ArrayList())
  12.        Private objEndPoint As IPEndPoint
  13.        Private ID As Integer = 0
  14.        Private BufData As Byte() = New Byte(65536) {}
  15.        Public Event DatosRecibidos(ByVal Datos() As Byte, ByVal SocketID As Integer)
  16.        Public Event ErrorCatched(ByVal msg As String)
  17.        Public Event Desconectado()
  18.        Public Event Conectado(ByVal SocketID As Integer)
  19. #End Region
  20.  
  21. #Region " Procedimientos "
  22.        Public Sub Conectar(ByVal vsIp As String, ByVal viPuerto As Integer)
  23.            Try
  24.                If Socket IsNot Nothing Then
  25.                    If Socket.Connected Then
  26.                        Call Desconectar()
  27.                    End If
  28.                End If
  29.                Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
  30.                Socket.NoDelay = True
  31.                Socket.DontFragment = False
  32.                Socket.LingerState.Enabled = True
  33.                Socket.LingerState.LingerTime = 100
  34.                Socket.SendBufferSize = 65536
  35.                Socket.ReceiveBufferSize = 65536
  36.                Dim endpoint As Net.IPEndPoint
  37.                endpoint = New IPEndPoint(IPAddress.Parse(vsIp), viPuerto)
  38.                Socket.Connect(endpoint)
  39.  
  40.                If Socket.Connected Then
  41.                    objEndPoint = CType(Socket.RemoteEndPoint, IPEndPoint)
  42.                    Call EsperaDeDatos()
  43.                End If
  44.            Catch ex As SocketException
  45.                RaiseEvent ErrorCatched(ex.Message)
  46.            End Try
  47.        End Sub
  48.        Public Sub Desconectar()
  49.            Try
  50.                If Socket IsNot Nothing Then
  51.                    If Socket.Connected Then
  52.                        Socket.Disconnect(True)
  53.                    End If
  54.                    Socket.Close()
  55.                    Socket = Nothing
  56.                End If
  57.                RaiseEvent Desconectado()
  58.            Catch SE As SocketException
  59.                RaiseEvent ErrorCatched(SE.Message)
  60.            End Try
  61.        End Sub
  62.        Public Sub Desconectar(ByVal SocketID As Integer)
  63.            DropClient(GetSocketPacket(SocketID), False, False)
  64.        End Sub
  65.        Public Function EnviarMensaje(ByVal SocketID As Integer, ByVal Datos() As Byte) As Boolean
  66.  
  67.            Try
  68.                If GetSocketPacket(SocketID).mClientSocket.Connected Then
  69.                    GetSocketPacket(SocketID).mClientSocket.Send(Datos)
  70.                    Return (True)
  71.                Else
  72.                    Return (False)
  73.                End If
  74.            Catch
  75.                Return (False)
  76.            End Try
  77.        End Function
  78.  
  79.        Public Function EnviarMensaje(ByVal SocketID As Integer, ByVal Mensaje As String) As Boolean
  80.            Try
  81.                If GetSocketPacket(SocketID).mClientSocket.Connected Then
  82.                    Dim NetStream As New NetworkStream(GetSocketPacket(SocketID).mClientSocket)
  83.  
  84.                    Dim SocketStream As New StreamWriter(NetStream)
  85.                    SocketStream.Write(Mensaje)
  86.  
  87.                    SocketStream.Flush()
  88.                    Return (True)
  89.                Else
  90.                    Return (False)
  91.                End If
  92.            Catch
  93.                Return (False)
  94.            End Try
  95.        End Function
  96.  
  97.  
  98. #End Region
  99.  
  100. #Region " Procedimientos Privados "
  101.        Private Sub EsperaDeDatos()
  102.            Try
  103.                If CallBackHandler Is Nothing Then
  104.                    CallBackHandler = New AsyncCallback(AddressOf OnDataReceived)
  105.                End If
  106.                Dim socketId As Integer = 1
  107.                If ClientList.Count > 0 Then
  108.                    socketId = TryCast(ClientList(ClientList.Count - 1), SocketPacket).mSocketID + 1
  109.                End If
  110.                Dim ConnectedClient As New SocketPacket(Socket, socketId)
  111.                ClientList.Add(ConnectedClient)
  112.                ID += 1
  113.                Socket.BeginReceive(BufData, 0, BufData.Length, SocketFlags.None, CallBackHandler, Socket)
  114.                RaiseEvent Conectado(ConnectedClient.mSocketID)
  115.            Catch SE As SocketException
  116.                RaiseEvent ErrorCatched(SE.Message)
  117.            Catch E As Exception
  118.                RaiseEvent ErrorCatched(E.Message)
  119.            End Try
  120.        End Sub
  121.        Private Sub OnDataReceived(ByVal Asyn As IAsyncResult)
  122.            Try
  123.                Dim ConnectedClient As SocketPacket = DirectCast(Asyn.AsyncState, SocketPacket)
  124.                If Not ConnectedClient.mClientSocket.Connected Then
  125.                    Return
  126.                End If
  127.                Dim CollectedDataLength As Integer = Socket.EndReceive(Asyn)
  128.                If CollectedDataLength = 0 Then
  129.                    If ConnectedClient.mClientSocket.Connected Then
  130.                        ConnectedClient.mClientSocket.Disconnect(False)
  131.                    End If
  132.                    ConnectedClient.mClientSocket.Close()
  133.  
  134.                    RaiseEvent Desconectado()
  135.                Else
  136.                    RaiseEvent DatosRecibidos(BufData, ConnectedClient.mSocketID)
  137.                    EsperaDeDatos()
  138.                End If
  139.            Catch generatedExceptionName As ObjectDisposedException
  140.                RaiseEvent Desconectado()
  141.            Catch SE As SocketException
  142.                If SE.ErrorCode = 10054 Then
  143.                    RaiseEvent Desconectado()
  144.                Else
  145.                    RaiseEvent ErrorCatched(SE.Message)
  146.                End If
  147.            Catch E As Exception
  148.                RaiseEvent ErrorCatched(E.Message)
  149.            End Try
  150.        End Sub
  151.        Private Sub DropClient(ByVal DisposedSocket As SocketPacket, ByVal DisconnectedRemotly As Boolean, ByVal DisconnectedForcibly As Boolean) 'tirar clientes
  152.            Try
  153.  
  154.                DisposedSocket.mClientSocket.Shutdown(SocketShutdown.Both)
  155.            Catch
  156.            End Try
  157.  
  158.  
  159.            Dim IsRemoved As Boolean = False
  160.  
  161.  
  162.            SyncLock ClientList.SyncRoot
  163.                Try
  164.  
  165.                    Dim SckID As Integer = 0
  166.                    While Not IsRemoved AndAlso (SckID < ClientList.Count)
  167.  
  168.                        Dim ClientSocket As SocketPacket = DirectCast(ClientList(SckID), SocketPacket)
  169.  
  170.  
  171.                        If ClientSocket.mClientSocket Is DisposedSocket.mClientSocket Then
  172.  
  173.                            ClientList.Remove(ClientSocket)
  174.  
  175.                            ID -= 1
  176.  
  177.                            IsRemoved = True
  178.  
  179.                            RaiseEvent Desconectado()
  180.                        End If
  181.                        SckID += 1
  182.                    End While
  183.                Catch E As Exception
  184.                    RaiseEvent ErrorCatched(E.Message)
  185.                End Try
  186.            End SyncLock
  187.        End Sub
  188.        Private Function GetSocketPacket(ByVal SocketID As Integer) As SocketPacket ' obtener paquetes del socket
  189.  
  190.            Dim mClientSocket As SocketPacket = Nothing
  191.  
  192.            For Each ClientSocket As SocketPacket In ClientList
  193.  
  194.                If ClientSocket.mSocketID = SocketID Then
  195.  
  196.                    mClientSocket = ClientSocket
  197.  
  198.                    Exit For
  199.                End If
  200.            Next
  201.            Return (mClientSocket)
  202.        End Function
  203.  
  204. #End Region
  205.  
  206. #Region "propiedades"
  207.        Public ReadOnly Property IsConectado() As Boolean
  208.            Get
  209.                Return Socket.Connected
  210.            End Get
  211.        End Property
  212.  
  213.        Public ReadOnly Property RemoteEndPoint() As System.Net.IPEndPoint
  214.            Get
  215.                Return objEndPoint
  216.            End Get
  217.        End Property
  218.        Public ReadOnly Property TotalConectado As Integer
  219.            Get
  220.                Return ID
  221.            End Get
  222.        End Property
  223. #End Region
  224.  
  225. #Region "Rem -> [ Socket Packet Helper Class ]"
  226.        Class SocketPacket
  227.            Friend ReadOnly mClientSocket As Socket
  228.            Friend ReadOnly mSocketID As Integer
  229.  
  230.            Public Sub New(ByVal ClientSocket As Socket, ByVal SocketID As Integer)
  231.                mClientSocket = ClientSocket
  232.                mSocketID = SocketID
  233.            End Sub
  234.        End Class
  235. #End Region
  236.  
  237. #Region " IDisposable Support "
  238.  
  239.        Private disposedValue As Boolean = False        ' Para detectar llamadas redundantes
  240.  
  241.        ' IDisposable
  242.        Protected Overridable Sub Dispose(ByVal disposing As Boolean)
  243.            If Not Me.disposedValue Then
  244.                If disposing Then
  245.                    ' TODO: Liberar otro estado (objetos administrados).
  246.                End If
  247.  
  248.                ' TODO: Liberar su propio estado (objetos no administrados).
  249.                ' TODO: Establecer campos grandes como Null.
  250.            End If
  251.            Me.disposedValue = True
  252.        End Sub
  253.        ' Visual Basic agregó este código para implementar correctamente el modelo descartable.
  254.        Public Sub Dispose() Implements IDisposable.Dispose
  255.            ' No cambie este código. Coloque el código de limpieza en Dispose (ByVal que se dispone como Boolean).
  256.            Dispose(True)
  257.            GC.SuppressFinalize(Me)
  258.        End Sub
  259. #End Region
  260.  
  261.    End Class
  262. End Namespace


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines