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

 

 


Tema destacado:


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Socket Asincronico !
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Socket Asincronico !  (Leído 2,472 veces)
TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Socket Asincronico !
« en: 8 Agosto 2016, 17:34 pm »

Toy trabajando con este proyecto

http://tech.reboot.pro/showthread.php?tid=86&highlight=sockets

Y le falta la opción de que el cliente pueda enviar datos al servidor.

El desarrollador añadio esto en el cliente

Código
  1.    Private Sub Send(ByVal msg As String, ByVal clientSocket As Socket)
  2.        'get bytes to send
  3.        Dim sendBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(msg)
  4.        'begin sending (notice the client is sent as an AsyncState)
  5.  
  6.        clientSocket.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSend), clientSocket)
  7.    End Sub
  8.  
  9.    Private Sub OnSend(ByVal ar As IAsyncResult)
  10.        Dim client As Socket = ar.AsyncState
  11.        client.EndSend(ar)
  12.    End Sub
  13.  

Esto al parecer funciona y digo al parecer porque aun no logro recibirlo en el servidor, el autor dice que para ello usen el mismo codigo que tiene el cliente, lo añado y sigue sin funcionar

Código
  1.    Private Sub OnAccept(ByVal ar As IAsyncResult)
  2.        clientSocket = serverSocket.EndAccept(ar)
  3.        serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
  4.        AddClient(clientSocket)
  5. 'Línea añadida para recibir dato        
  6. clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), clientSocket)
  7.  
  8.    End Sub
  9.  
  10.    Private Sub OnRecieve(ByVal ar As IAsyncResult)
  11.        Dim client As Socket = ar.AsyncState
  12.        client.EndReceive(ar)
  13.        Dim bytesRec As Byte() = byteData
  14.        Dim message As String = System.Text.Encoding.ASCII.GetString(bytesRec)
  15.        Read(message)
  16.        clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), clientSocket)
  17.    End Sub
  18.  
  19.    Delegate Sub _Read(ByVal msg As String)
  20.    Private Sub Read(ByVal msg As String)
  21.        If InvokeRequired Then
  22.            Invoke(New _Read(AddressOf Read), msg)
  23.            Exit Sub
  24.        End If
  25.        RichTextBox1.Text &= msg
  26.    End Sub
  27.  
  28.  

Depurandolo nunca entra en esos metodos unicamente cuando cierro el cliente es que el entonces entra y genera un error porque el socket esta cerrado y no puede leer nada.

Alguna idea..

Salu2


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.807



Ver Perfil
Re: Socket Asincronico !
« Respuesta #1 en: 8 Agosto 2016, 18:02 pm »

Depurandolo nunca entra en esos metodos

genera un error porque el socket esta cerrado

Alguna idea..

¿Te has asegurado de establecer la conexión del Socket? (como lo muestra el autor de código):

Citar
Código
  1.    Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
  2.        clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
  3.        Dim ipAddress As IPAddress = ipAddress.Parse("127.0.0.1")
  4.        Dim ipEndPoint As IPEndPoint = New IPEndPoint(ipAddress, 8800)
  5.        clientSocket.BeginConnect(ipEndPoint, New AsyncCallback(AddressOf OnConnect), Nothing)
  6.    End Sub

Ese método supuestamente debería llamar de forma asincrónica al método OnConnect, y éste último a OnRecieve.

Saludos


En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Re: Socket Asincronico !
« Respuesta #2 en: 9 Agosto 2016, 03:26 am »

Yo creo que si esta conectado porque logro enviar el mensaje sin problemas desde el SERVIDOR para el CLIENTE, y quiero poder hacer lo mismo del CLIENTE para el SERVIDOR, nada mas entra en ese Sub cuando cierro el Socket !!

Salu2 y gracias cualquier ayuda !!
En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Re: Socket Asincronico !
« Respuesta #3 en: 9 Agosto 2016, 17:33 pm »

No me habia fijado de que el codigo que muestras es del cliente pero yo me refiero al lado del servidor que no esta recibiendo lo que envio desde el cliente.

Salu2
En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Re: Socket Asincronico !
« Respuesta #4 en: 11 Agosto 2016, 02:30 am »

Código
  1. Imports System.Net
  2. Imports System.Net.Sockets
  3. Imports System.Text
  4. Imports System.Threading
  5.  
  6. ' State object for reading client data asynchronously
  7.  
  8. Public Class StateObject
  9.    ' Client  socket.
  10.    Public workSocket As Socket = Nothing
  11.    ' Size of receive buffer.
  12.    Public Const BufferSize As Integer = 1024
  13.    ' Receive buffer.
  14.    Public buffer(BufferSize) As Byte
  15.    ' Received data string.
  16.    Public sb As New StringBuilder
  17. End Class 'StateObject
  18.  
  19.  
  20. Public Class AsynchronousSocketListener
  21.    ' Thread signal.
  22.    Public Shared allDone As New ManualResetEvent(False)
  23.    Public Shared ClientsInfo As New List(Of UserInfo)
  24.  
  25.    ' This server waits for a connection and then uses  asychronous operations to
  26.    ' accept the connection, get data from the connected client,
  27.    ' echo that data back to the connected client.
  28.    ' It then disconnects from the client and waits for another client.
  29.    Public Shared Sub Escuchar()
  30.        ' Data buffer for incoming data.
  31.        Dim bytes() As Byte = New [Byte](1023) {}
  32.  
  33.        ' Establish the local endpoint for the socket.
  34.        Dim IpEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 11000)
  35.  
  36.        ' Create a TCP/IP socket.
  37.        Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
  38.  
  39.        ' Bind the socket to the local endpoint and listen for incoming connections.
  40.        listener.Bind(IpEndPoint)
  41.        listener.Listen(100)
  42.  
  43.        While True
  44.            ' Set the event to nonsignaled state.
  45.            allDone.Reset()
  46.  
  47.            ' Start an asynchronous socket to listen for connections.
  48.            'MessageBox.Show("Waiting for a connection...", "Server Side")
  49.            listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), listener)
  50.  
  51.            ' Wait until a connection is made and processed before continuing.
  52.            allDone.WaitOne()
  53.        End While
  54.  
  55.    End Sub 'Main
  56.  
  57.    Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
  58.        ' Get the socket that handles the client request.
  59.        Dim listener As Socket = CType(ar.AsyncState, Socket)
  60.        ' End the operation.
  61.        Dim handler As Socket = listener.EndAccept(ar)
  62.  
  63.        ' Create the state object for the async receive.
  64.        Dim state As New StateObject
  65.        state.workSocket = handler
  66.        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
  67.    End Sub 'AcceptCallback
  68.  
  69.    Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
  70.        Dim content As String = String.Empty
  71.  
  72.        ' Retrieve the state object and the handler socket
  73.        ' from the asynchronous state object.
  74.        Dim state As StateObject = CType(ar.AsyncState, StateObject)
  75.        Dim handler As Socket = state.workSocket
  76.  
  77.        ' Read data from the client socket.
  78.        Dim bytesRead As Integer = handler.EndReceive(ar)
  79.  
  80.        If bytesRead > 0 Then
  81.            ' There  might be more data, so store the data received so far.
  82.            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))
  83.  
  84.            ' Check for end-of-file tag. If it is not there, read
  85.            ' more data.
  86.            content = state.sb.ToString()
  87.            If content.IndexOf("<EOF>") > -1 Then
  88.                ' All the data has been read from the
  89.                ' client.
  90.                MessageBox.Show("Read {0} bytes from socket. " + vbLf + " Data : {1}", content.Length, content)
  91.                MessageBox.Show(content, "Server Side")
  92.  
  93.                Send(handler, content)
  94.            Else
  95.                ' Not all data received. Get more.
  96.                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
  97.            End If
  98.        End If
  99.    End Sub 'ReadCallback
  100.  
  101.    Private Shared Sub Send(ByVal handler As Socket, ByVal data As String)
  102.        ' Convert the string data to byte data using ASCII encoding.
  103.        Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)
  104.  
  105.        ' Begin sending the data to the remote device.
  106.        handler.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), handler)
  107.    End Sub 'Send
  108.  
  109.    Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
  110.        ' Retrieve the socket from the state object.
  111.        Dim handler As Socket = CType(ar.AsyncState, Socket)
  112.  
  113.        ' Complete sending the data to the remote device.
  114.        Dim bytesSent As Integer = handler.EndSend(ar)
  115.        MessageBox.Show("Sent" & bytesSent & " bytes to client.", "Server Side")
  116.  
  117.        handler.Shutdown(SocketShutdown.Both)
  118.        handler.Close()
  119.        ' Signal the main thread to continue.
  120.        allDone.Set()
  121.    End Sub 'SendCallback
  122.  
  123. End Class 'AsynchronousSocketListener
  124.  

Como puedo acomodar tu codigo:

Código
  1.    Dim userInfo As UserInfo = UserInfo.FromStream(buferr completo de los datos recibidos por el socket)
  2.    users.Add(userInfo)

Gracias de antemano

« Última modificación: 11 Agosto 2016, 02:34 am por TrashAmbishion » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
No-Ip Y socket
Programación Visual Basic
n3ts4mura1 0 1,227 Último mensaje 15 Agosto 2006, 20:20 pm
por n3ts4mura1
Raw socket
Programación Visual Basic
yeikos 3 2,400 Último mensaje 28 Agosto 2007, 15:53 pm
por elmaro
Multithread Socket (Thread per Socket)not Complete « 1 2 »
Programación Visual Basic
ntaryl 12 8,825 Último mensaje 10 Febrero 2012, 18:42 pm
por ntaryl
Socket en Dev c++
Programación C/C++
davidzelaya 0 3,782 Último mensaje 13 Septiembre 2012, 06:45 am
por davidzelaya
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines