2013-08-27 3 views
-1

example of Microsoft (Visual Basic의 경우 4.5 순) 보내 datas는 소켓을 던져하지만,이 블록은 항상 true입니다받을 :EndReceive 결코 결코 수신되지 완료 비주얼 베이직 닷넷 내가 사용하고

Private Sub OnRecieve(ByVal ar As IAsyncResult) 
    Try 
     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)) 

      ' Se supone que vuelve por los datos que faltan, pero no lo hace (Creo) 
      client.BeginReceive(state.buffer, 0, state.BufferSize, 0, AddressOf OnRecieve, state) 

     Else 
      ' All the data has arrived; put it in response. 
      If state.sb.Length > 1 Then 
       VariablesGlobales.response = state.sb.ToString() 
      End If 
      ' Signal that all bytes have been received. 
      receiveDone.Set() 
     End If 


    Catch ex As Exception 
     'clientSocket.Close() 
     RaiseEvent FallaAlRecibirDatos(ex.Message, "Falla en endReive.") 
    End Try 

End Sub 

하지만 보내 보내 짧거나 큰 메시지를 보내면 절대로 다른 문장을 입력 할 수 없습니다. 여기, 내 초기 코드 :

Public Sub Conectar() 

    clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) 

    Dim ipEndPoint As IPEndPoint = New IPEndPoint(Me.ipAddress, VariablesGlobales.Puerto) 
    clientSocket.BeginConnect(ipEndPoint, New AsyncCallback(AddressOf OnConnect), clientSocket) 

    ' Wait for connect. 
    connectDone.WaitOne() 

    EnviarDatosPersonales() 

    ' Wait for send datas. 
    sendDone.WaitOne() 

    While True 
     AvtivarEscuchador() 
     receiveDone.WaitOne() 

     DescifrarMsg(VariablesGlobales.response) 
    End While 
End Sub 

내가, 내가 서버가 보내는 메시지를 받아 봐하지, 나는 단계에 비주얼 스튜디오 단계에서 그들을 볼 수 있지만, 그것은 결코 다른 사람에 들어 가지 이유는 모르겠어요 데이터 수신을 완료하지 못합니다.

나는 the answer of Marc Gravell을 읽었지만 이것을 해결하는 방법에 대한 코드 예제를 선호합니다. 어떻게해야할지 몰랐습니다.

또한 "else"를 제거하고 내 textBox를 많은 흰색 선으로 채 웁니다. 도와주세요. 감사.

죄송합니다 아, 여기 Escuchador 기능입니다 : 이미 마크 Gravell의 대답에 링크로

Private Sub AvtivarEscuchador() 

    ' Borramos los datos de respuesta anterior 
    VariablesGlobales.response = "" 

    ' Activamos el escuchador 
    Try 
     ' Create the state object. 
     Dim state As New StateObject() 
     state.workSocket = Me.clientSocket 

     ' Begin receiving the data from the remote device. 
     Me.clientSocket.BeginReceive(state.buffer, 0, state.BufferSize, 0, AddressOf OnRecieve, state) 
    Catch e As Exception 
     RaiseEvent FallaAlRecibirDatos("No se pudo activar el escuchador.", "Falla al intentar escuchar.") 
    End Try 

End Sub 
+0

당신이 적어도 한 번'client.BeginReceive' 호출 한 :

그리고 당신 같은

여기에 주석 코드가 어디에 추가 부품을 배치하는 것입니다, 일부 코드를 요청했습니다? 'bytesRead'의 초기 값은 무엇입니까? – I4V

+0

나는 더 많은 코드로 질문을 편집했다. – bluesky777

+0

bluesky777, 나는 아직도 당신이'BeginReceive'를 호출하는 것을 보지 못합니다. 'BeginRecv'를 호출하지 않을 때'OnRecieve'가 호출 될 것이라고 어떻게 생각하십니까 – I4V

답변

0

, 중요한 일에 자신의 첫 번째 문장 :

"EndReceive 잘 공을받을 수 있습니다 스트림이 닫힌 경우이고 모든 데이터가 소비되었습니다. "

스트림이 열려있는 한 EndReceive에서 절대로 0을 얻지 못할 것입니다. 프로토콜에 따라 보유한 데이터를 처리하여 메시지의 끝을 찾고 응답을 보내야합니다.

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

    ' Put here code to check for protocol end (for example \0) in your buffer state.sb 
    ' and handle protocol if found. The rest of the buffer should remain in the buffer 
    ' as it could be part of the next protocol. 

    ' if you only except one message, set receiveDone.Set() here if message received 
    ' completely 

    ' Se supone que vuelve por los datos que faltan, pero no lo hace (Creo) 
    client.BeginReceive(state.buffer, 0, state.BufferSize, 0, AddressOf OnRecieve, state) 

Else 
    'connection was closed 
    ' handle existing information if appropreate 
    receiveDone.Set() 
End If 
+0

감사합니다. 그러나 Microsoft 예제에서는 표시되지 않았습니다. 보시다시피, 나는 DescifrarMsg (VariablesGlobales.response) 함수를 호출하여 데이터를 처리하고 채팅 텍스트 상자에 응답을 삽입합니다. 데이터를받는 것을 끝내고 계속 듣기를 원한다면 Socket을 닫아야합니까? PD : 내 질문에 -1이있는 이유는 무엇입니까 ?? : O – bluesky777

+0

"코드"로 답변을 업데이트하십시오. 소켓을 닫을 필요없이 수신 한 모든 데이터를 처리하고 '\ 0'과 같은 최종 정보가있는 방식으로 프로토콜을 선택하면됩니다. –

+0

감사합니다. 나는 이것을 다음과 같이 사용했다. **If** state.sb.ToString.Contains("\0") Then **Dim** textoMsg As String = state.sb.ToString **textoMsg** = textoMsg.Substring(0, textoMsg.LastIndexOf("\0")) **DescifrarMsg(textoMsg)** Return End If 그리고 작동 중이다. 계속 진행할 수 있으며, 대단히 감사합니다. 행복하게 :) – bluesky777