2012-06-11 2 views
1

내 컴퓨터 (LocalHost)에서 실행되는 서버 응용 프로그램에서 하나의 응답 만받는 이유를 파악하는 데 문제가 있습니다. 이 서버 응용 프로그램의 소스가 없지만 Java 응용 프로그램입니다. 보낸 메시지는 xml 구조이며 EoT 태그로 끝나야합니다.C# 소켓. 오직 첫 번째 메시지 만받을 수 있습니다.

통신 :

  1. 클라이언트가 단절 연결합니다.
  2. 클라이언트가 서버에 메시지를 보냅니다.
  3. 서버는 클라이언트에게 recived 메시지를 보냅니다.
  4. 클라이언트가 서버에 메시지를 보냅니다.
  5. 서버에서 전송 종료 문자를 보냅니다.
  6. 클라이언트가 서버에 메시지를 보냅니다.
  7. 서버에서 전송 종료 문자를 보냅니다.

이 내 클라이언트가 연결 전송 및 수신하는 방법입니다

public bool ConnectSocket(string server, int port) 
{ 
System.Net.IPHostEntry hostEntry = null; 

    try 
    { 
     // Get host related information. 
     hostEntry = System.Net.Dns.GetHostEntry(server); 
    } 
    catch (System.Exception ex) 
    { 
      return false; 
    } 


    // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid 
    // an exception that occurs when the host IP Address is not compatible with the address family 
    // (typical in the IPv6 case). 
    foreach (System.Net.IPAddress address in hostEntry.AddressList) 
    { 
      System.Net.IPEndPoint ipe = new System.Net.IPEndPoint(address, port); 
      System.Net.Sockets.Socket tempSocket = new System.Net.Sockets.Socket(ipe.AddressFamily, System.Net.Sockets.SocketType.Stream, 
                       System.Net.Sockets.ProtocolType.Tcp); 
      tempSocket.Connect(ipe); 

      if (tempSocket.Connected) 
      { 
       m_pSocket = tempSocket; 
       m_pSocket.NoDelay = true; 
       return true; 
      } 
      else 
       continue; 
     } 
     return false; 
    } 
} 

public void Send(string message) 
{ 
    message += (char)4;//We add end of transmission character 
    m_pSocket.Send(m_Encoding.GetBytes(message.ToCharArray())); 
} 

private void Recive() 
{ 
    byte[] tByte = new byte[1024]; 
    m_pSocket.Receive(tByte); 
    string recivemessage = (m_Encoding.GetString(tByte)); 
} 

답변

3

귀하의 Receive 코드는 매우 잘못된 보인다; 패킷이 서버가 메시지를 보내는 것과 동일한 구성에 도착한다고 가정해서는 안됩니다. TCP는 단지 스트림입니다. 따라서 : Receive에서의 반송파를 받아야 수신 한 바이트 수를 확인해야합니다. 하나의 메시지, 전체 메시지, 여러 개의 전체 메시지 또는 하나의 메시지의 마지막 부분과 다음의 첫 번째 부분의 일부일 수 있습니다. 일반적으로 "LF 문자로 분리 된 메시지"를 의미하거나 "각 메시지 길이에 네트워크 바이트 순서 정수 4 바이트가 접두사로 사용됩니다"라는 의미 일 수있는 일종의 "프레이밍"결정이 필요합니다. 이는 일반적으로 전체 프레임이 생길 때까지 버퍼링해야 함을 의미하며, 은 다음 프레임의 일부인 버퍼 끝에 여분의 데이터가있을 것을 염려합니다. 키 비트는하지만, 추가 : 특히

int bytes = m_pSocket.Receive(tByte); 
// now process "bytes" bytes **only** from tByte, nothing that this 
// could be part of a message, an entire message, several messages, or 
// the end of message "A", the entire of message "B", and the first byte of 
// message "C" (which might not be an entire character) 

를 텍스트 형식으로, 당신 할 수있는 멀티 바이트 문자가 두 개의 메시지 사이에 분할 될 수 있기 때문에 당신이, 버퍼 전체 메시지를 확인하기 전까지되지 시작 디코딩 .

수신 루프에도 문제가있을 수 있지만 표시하지 않으므로 (아무 것도 Receive) 호출 할 수 없으므로 주석을 달 수 없습니다.

관련 문제