none
vb.net et sockets RRS feed

  • Question

  • Bonjour,

    j'utilise un socket pour envoyer des commandes à une application qui tourne sur un serveur. Je n'ai pas les sources de cette appli.

    Mon code ouvre bien un socket et envoie bien la commande (je la vois bien passer dans l'historique de l'appli et l'action est executée). Le problème est que j'ai plusieurs commande à envoyer daffilé et que le socket est déconnecté, la deuxième commande est envoyée, mais ne passe pas dans l'historique et pas d'actions executée, et la commande "beginReceive" revoie l'erreur : "Une connection établie a été abandonnée par un logiciel de votre ordinateur hôte".

    voilà mon code :

    dans le formulaire:

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            AsynchronousClient.Connect()
            AsynchronousClient.ConnectSend("XMM138")
            System.Threading.Thread.Sleep(2000)
            AsynchronousClient.ConnectSend("XMM250")
            AsynchronousClient.EndConnect()
        End Sub

    ma classe :

    Imports System Imports System.Net Imports System.Net.Sockets Imports System.Threading Imports System.Text ' State object for receiving data from remote device. Public Class StateObject ' Client socket. Public workSocket As Socket = Nothing ' Size of receive buffer. Public Const BufferSize As Integer = 256 ' Receive buffer. Public buffer(BufferSize) As Byte ' Received data string. Public sb As New StringBuilder End Class 'StateObject Public Class AsynchronousClient ' The port number for the remote device. Private Const port As Integer = 2034 ' ManualResetEvent instances signal completion. Private Shared connectDone As New ManualResetEvent(False) Private Shared sendDone As New ManualResetEvent(False) Private Shared receiveDone As New ManualResetEvent(False) Public Shared ipHostInfo As IPHostEntry = Dns.GetHostEntry("DEIMOS") 'Dns.GetHostName()) Public Shared ipAddress As IPAddress = ipHostInfo.AddressList(0) Public Shared remoteEP As New IPEndPoint(ipAddress, port) ' Create a TCP/IP socket. Public Shared client As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) ' The response from the remote device. Private Shared response As String = String.Empty Public Shared Sub Connect() ' Connect to the remote endpoint. client.BeginConnect(remoteEP, New AsyncCallback(AddressOf ConnectCallback), client) ' Wait for connect. connectDone.WaitOne() End Sub Public Shared Sub ConnectSend(ByVal Commande As String) ' Establish the remote endpoint for the socket. ' For this example use local machine. 'Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName()) ' Send test data to the remote device. Dim Donnee As String = "<?xml version=""1.0"" encoding=""ISO-8859-1""?><commandes><commande id=""1""><numDossier>001</numDossier><commandeSIA>" & Commande & "/OP1</commandeSIA></commande></commandes>" Donnee = "GET /commandeUG HTTP/1.1" & vbCr & "Connection: Close" & vbCr & "Content-Length: " & Donnee.Length & vbCr & vbCr & Donnee & vbCr Send(client, Donnee) 'Thread.Sleep(1000) sendDone.WaitOne() ' Receive the response from the remote device. Receive(client) 'Thread.Sleep(1000) receiveDone.WaitOne() ' Write the response to the console. 'Console.WriteLine("Response received : {0}", response) 'MsgBox(response) End Sub 'Main Public Shared Sub EndConnect() ' Release the socket. client.Shutdown(SocketShutdown.Both) client.Close() End Sub Private Shared Sub ConnectCallback(ByVal ar As IAsyncResult) Try ' Retrieve the socket from the state object. Dim client As Socket = CType(ar.AsyncState, Socket) ' Complete the connection. client.EndConnect(ar) 'Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString()) 'MsgBox(client.RemoteEndPoint.ToString()) ' Signal that the connection has been made. connectDone.Set() Catch ex As Exception MsgBox(ex.Message) End Try End Sub 'ConnectCallback Private Shared Sub Receive(ByVal client As Socket) Try ' Create the state object. Dim state As New StateObject state.workSocket = client If client.Connected Then ' Begin receiving the data from the remote device. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state) Else MsgBox("déconnecté") End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub 'Receive Private Shared Sub ReceiveCallback(ByVal ar As IAsyncResult) ' Retrieve the state object and the client socket ' from the asynchronous state object. Dim state As StateObject = CType(ar.AsyncState, StateObject) Dim client As Socket = state.workSocket ' Read data from the remote device. Dim bytesRead As Integer = client.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)) ' Get the rest of the data. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state) Else ' All the data has arrived; put it in response. If state.sb.Length > 1 Then response = state.sb.ToString() End If ' Signal that all bytes have been received. receiveDone.Set() End If End Sub 'ReceiveCallback Private Shared Sub Send(ByVal client As Socket, ByVal data As String) ' Convert the string data to byte data using ASCII encoding. Dim byteData As Byte() = Encoding.ASCII.GetBytes(data) If client.Connected Then ' Begin sending the data to the remote device. client.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), client) Else Connect() ' Begin sending the data to the remote device. client.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), client) End If End Sub 'Send Private Shared Sub SendCallback(ByVal ar As IAsyncResult) ' Retrieve the socket from the state object. Dim client As Socket = CType(ar.AsyncState, Socket) ' Complete sending the data to the remote device. Dim bytesSent As Integer = client.EndSend(ar) 'Console.WriteLine("Sent {0} bytes to server.", bytesSent) 'MsgBox(bytesSent) ' Signal that all bytes have been sent. sendDone.Set() End Sub 'SendCallback End Class 'AsynchronousClien

    le "BeginReceive" qui génère l'erreur au deuxieme passage est dans la sub "Receive".

    Si quelqu'un pouvait me dire ce que je fais de mal, et m'aider.....MERCI!!!!!

    Fabienne 


    Fab!

    vendredi 7 février 2014 09:17

Réponses

Toutes les réponses