2011-03-13 6 views
2

내 서버에 들어오는 패킷을 처리하는 코드를 대부분 작성했습니다. 패킷의 형식은 항상 int/int/int/string/string이고 첫 번째 int는 패킷의 크기입니다. 나는 전체 패킷이 도착했는지, 또는 더 많은 조각이 들어올 때까지 기다릴 필요가 있는지 확인하고 코드를 작성한 방식으로 어떤 좋은 방법을 생각할 수 없는지를 확인하고 확인할 수있는 방법을 찾아야합니다. 내 두뇌가 아마 이것을 overthinking로 어떤 도움이 좋을 것입니다.분할 TCP 패킷 읽기

private void ReadClientPacket(object client) 
{ 
    TcpClient tcpClient = (TcpClient)client; 
    NetworkStream clientStream = tcpClient.GetStream(); 

    while (true) 
    { 
     try 
     { 
      int packetsize; 

      // Create a new Packet Object and fill out the data from the incoming TCP Packets 
      RCONPacket packet = new RCONPacket(); 

      using (BinaryReader reader = new BinaryReader(clientStream)) 
      { 
       // First Int32 is Packet Size 
       packetsize = reader.ReadInt32(); 

       packet.RequestId = reader.ReadInt32(); 
       packet.ServerDataSent = (RCONPacket.SERVERDATA_sent)reader.ReadInt32(); 

       Console.WriteLine("Packet Size: {0} RequestID: {1} ServerData: {2}", packetsize, packet.RequestId, packet.ServerDataSent); 

       // Read first and second String in the Packet (UTF8 Null Terminated) 
       packet.String1 = ReadBytesString(reader); 
       packet.String2 = ReadBytesString(reader); 

       Console.WriteLine("String1: {0} String2: {1}", packet.String1, packet.String2); 
      } 

      switch (packet.ServerDataSent) 
      { 
       case RCONPacket.SERVERDATA_sent.SERVERDATA_AUTH: 
       { 
        ReplyAuthRequest(packet.RequestId, clientStream); 
        break; 
       } 
       case RCONPacket.SERVERDATA_sent.SERVERDATA_EXECCOMMAND: 
       { 
        ReplyExecCommand(); 
        break; 
       } 
       default: 
       { 
        break; 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
      break; 
     } 
    } 

    tcpClient.Close(); 
} 

답변

1

기본 스트림이 더 많은 데이터를 기다리므로 작업해야하는 작업. 즉, clientStream.ReadByte에 전화를 걸어 사용할 수있는 바이트가없는 경우 데이터가 들어올 때까지 또는 스트림이 닫힐 때까지 메서드가 차단됩니다.이 경우에는 서버에서 연결이 끊어졌습니다.

BinaryReader은 읽기 요청을 만족시킬만큼 충분한 데이터가있을 때까지 코드가 예상대로 작동해야합니다.

+0

대단히 감사합니다! –