Socket Asincronico !

Iniciado por TrashAmbishion, 8 Agosto 2016, 17:34 PM

0 Miembros y 1 Visitante están viendo este tema.

TrashAmbishion

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 (vbnet) [Seleccionar]

    Private Sub Send(ByVal msg As String, ByVal clientSocket As Socket)
        'get bytes to send
        Dim sendBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(msg)
        'begin sending (notice the client is sent as an AsyncState)

        clientSocket.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSend), clientSocket)
    End Sub

    Private Sub OnSend(ByVal ar As IAsyncResult)
        Dim client As Socket = ar.AsyncState
        client.EndSend(ar)
    End Sub


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 (vbnet) [Seleccionar]

    Private Sub OnAccept(ByVal ar As IAsyncResult)
        clientSocket = serverSocket.EndAccept(ar)
        serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
        AddClient(clientSocket)
'Línea añadida para recibir dato       
clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), clientSocket)

    End Sub

    Private Sub OnRecieve(ByVal ar As IAsyncResult)
        Dim client As Socket = ar.AsyncState
        client.EndReceive(ar)
        Dim bytesRec As Byte() = byteData
        Dim message As String = System.Text.Encoding.ASCII.GetString(bytesRec)
        Read(message)
        clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), clientSocket)
    End Sub

    Delegate Sub _Read(ByVal msg As String)
    Private Sub Read(ByVal msg As String)
        If InvokeRequired Then
            Invoke(New _Read(AddressOf Read), msg)
            Exit Sub
        End If
        RichTextBox1.Text &= msg
    End Sub



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

Eleкtro

Cita de: TrashAmbishion en  8 Agosto 2016, 17:34 PMDepurandolo 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 (vbnet,5) [Seleccionar]
    Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
        clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Dim ipAddress As IPAddress = ipAddress.Parse("127.0.0.1")
        Dim ipEndPoint As IPEndPoint = New IPEndPoint(ipAddress, 8800)
        clientSocket.BeginConnect(ipEndPoint, New AsyncCallback(AddressOf OnConnect), Nothing)
    End Sub

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

Saludos








TrashAmbishion

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 !!

TrashAmbishion

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

TrashAmbishion

#4
Código (vbnet) [Seleccionar]

Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading

' State object for reading client data asynchronously

Public Class StateObject
   ' Client  socket.
   Public workSocket As Socket = Nothing
   ' Size of receive buffer.
   Public Const BufferSize As Integer = 1024
   ' Receive buffer.
   Public buffer(BufferSize) As Byte
   ' Received data string.
   Public sb As New StringBuilder
End Class 'StateObject


Public Class AsynchronousSocketListener
   ' Thread signal.
   Public Shared allDone As New ManualResetEvent(False)
   Public Shared ClientsInfo As New List(Of UserInfo)

   ' This server waits for a connection and then uses  asychronous operations to
   ' accept the connection, get data from the connected client,
   ' echo that data back to the connected client.
   ' It then disconnects from the client and waits for another client.
   Public Shared Sub Escuchar()
       ' Data buffer for incoming data.
       Dim bytes() As Byte = New [Byte](1023) {}

       ' Establish the local endpoint for the socket.
       Dim IpEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 11000)

       ' Create a TCP/IP socket.
       Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

       ' Bind the socket to the local endpoint and listen for incoming connections.
       listener.Bind(IpEndPoint)
       listener.Listen(100)

       While True
           ' Set the event to nonsignaled state.
           allDone.Reset()

           ' Start an asynchronous socket to listen for connections.
           'MessageBox.Show("Waiting for a connection...", "Server Side")
           listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), listener)

           ' Wait until a connection is made and processed before continuing.
           allDone.WaitOne()
       End While

   End Sub 'Main

   Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
       ' Get the socket that handles the client request.
       Dim listener As Socket = CType(ar.AsyncState, Socket)
       ' End the operation.
       Dim handler As Socket = listener.EndAccept(ar)

       ' Create the state object for the async receive.
       Dim state As New StateObject
       state.workSocket = handler
       handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
   End Sub 'AcceptCallback

   Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
       Dim content As String = String.Empty

       ' Retrieve the state object and the handler socket
       ' from the asynchronous state object.
       Dim state As StateObject = CType(ar.AsyncState, StateObject)
       Dim handler As Socket = state.workSocket

       ' Read data from the client socket.
       Dim bytesRead As Integer = handler.EndReceive(ar)

       If bytesRead > 0 Then
           ' There  might be more data, so store the data received so far.
           state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))

           ' Check for end-of-file tag. If it is not there, read
           ' more data.
           content = state.sb.ToString()
           If content.IndexOf("<EOF>") > -1 Then
               ' All the data has been read from the
               ' client.
               MessageBox.Show("Read {0} bytes from socket. " + vbLf + " Data : {1}", content.Length, content)
               MessageBox.Show(content, "Server Side")
 
               Send(handler, content)
           Else
               ' Not all data received. Get more.
               handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
           End If
       End If
   End Sub 'ReadCallback

   Private Shared Sub Send(ByVal handler As Socket, ByVal data As String)
       ' Convert the string data to byte data using ASCII encoding.
       Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)

       ' Begin sending the data to the remote device.
       handler.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), handler)
   End Sub 'Send

   Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
       ' Retrieve the socket from the state object.
       Dim handler As Socket = CType(ar.AsyncState, Socket)

       ' Complete sending the data to the remote device.
       Dim bytesSent As Integer = handler.EndSend(ar)
       MessageBox.Show("Sent" & bytesSent & " bytes to client.", "Server Side")

       handler.Shutdown(SocketShutdown.Both)
       handler.Close()
       ' Signal the main thread to continue.
       allDone.Set()
   End Sub 'SendCallback

End Class 'AsynchronousSocketListener


Como puedo acomodar tu codigo:

Código (vbnet) [Seleccionar]
   Dim userInfo As UserInfo = UserInfo.FromStream(buferr completo de los datos recibidos por el socket)
   users.Add(userInfo)


Gracias de antemano