2017-12-06 1 views
-1

소켓에 익숙하지 않습니다. 이것은 서버에서 데이터를 보내고받는 코드입니다.TcpClient 소켓에서의 오류 처리

이 코드는 클라이언트가 서버에서 데이터를 수신 할 수있는 한 올바르게 작동합니다.

서버가 주어진 시간 내에 응답을 보내지 않으면 응용 프로그램에서 "응답 없음"을 전송해야합니다.

recvBuffer가 비어 있거나 NULL인지 어떻게 알 수 있습니까?

현재 recvBuffer에 대한 조건이 작동하지 않고 응용 프로그램이 "System.IndexOutOfRangeException error"라는 결과를 초래하는 빈 버퍼를 보내려고합니다.

class GetSocket 
{  
    public string SocketSendReceive(string server, int port, string cmd) 
    { 
     byte[] recvBuffer = new byte[1024]; 
     TcpClient tcpClient = new TcpClient(); 
     tcpClient.Client.ReceiveTimeout = 200; 

     try 
      { 
       tcpClient.Connect(server, 6100); 

      } 
      catch (SocketException e) 
      { 

       MessageBox.Show(e.Message); 

      } 

      if (tcpClient != null && tcpClient.Connected) 
      { 
       try 
       { 
        tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd)); 
        tcpClient.Client.Receive(recvBuffer); 

       } 

       catch (SocketException e) 
       { 
        MessageBox.Show(e.ErrorCode.ToString()); 
       } 

       tcpClient.GetStream().Close(); 
       tcpClient.Client.Close(); 
       tcpClient.Client.Dispose(); 
       tcpClient = null; 
       string tmp = Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length); 

       if (recvBuffer != null && recvBuffer.Length > 0) 
       { 
        string[] words = tmp.Split(null); 
        return words[1]; 
       } 
       else 
       { 
        return ("No Answer Received"); 
       } 
      } 
     return null; 
    } 

} 
+1

정지 (당신이 그것을 변경 아무것도하지 않을 때문에, null이 아닌 길이 1024 바이트 _ALWAYS_ 것) 등 모든 디코딩 물건은 '시도에 간다 코드를 리팩토링 수신 버퍼에보고 ''return ("No Answer ...")'부분이'catch' 블록에 들어가는 동안'Receive()'호출 후에 차단합니다. Throw되는'SocketException'은 타임 아웃이 발생한 것을 알려줍니다. 자세한 내용은 [해당 설명서를 참조하십시오 (https://msdn.microsoft.com/en-us/library/8s4y8aff (v = vs.110) .aspx) –

+0

안녕하세요 친절한 도움 주셔서 감사합니다, 코드 작동합니다. 나는 너에게 제안한 변화를했다. –

+0

문제를 직접 해결 한 경우 문제의 원인과 해결 방법을 설명하는 답변을 게시 한 다음 해당 대답을 수락 된 것으로 표시하십시오. –

답변

0

다음 코드는 제안 된대로 변경 한 후에 잘 작동합니다.

class GetSocket 
{  
    public string SocketSendReceive(string server, int port, string cmd) 
    { 
     byte[] recvBuffer = new byte[1024]; 
     TcpClient tcpClient = new TcpClient(); 
     tcpClient.Client.ReceiveTimeout = 200; 
     string tmp; 


      try 
      { 
       tcpClient.Connect(server, 6100); 

      } 
      catch (SocketException e) 
      { 

       MessageBox.Show(e.Message); 

      } 



      if (tcpClient != null && tcpClient.Connected) 
      { 
       try 
       { 
        tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd)); 
        tcpClient.Client.Receive(recvBuffer); 
        tmp = Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length); 
        string[] words = tmp.Split(null); 
        return words[1]; 

       } 

       catch (SocketException e) 
       { 
        return ("No Answer Received"); 
       } 

      } 
     return null; 
    } 


}