2014-04-04 178 views
0

我在約兩年內錯過了它併爲服務器編寫客戶端後正在練習C#。無論如何,問題是,Socket.Receive()似乎被卡住了(我的循環實際上並沒有通過測試)。這是我在Program.cs中的調用:Socket.Receive()卡住

   byte[] buffer = new byte[7]; 
       hSocket.Receive(buffer, 0, buffer.Length, 500);
這是我的APISocket.cs的片段
 public bool Connect(string ServerIP, int ServerPort, int Timeout) 
     { 
      TimeoutObject.Reset(); 
      SocketException = null; 
      try 
      { 
       Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
       IPEndPoint IPEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), ServerPort); 
       object state = new object(); 
       Socket.BeginConnect(IPEndPoint, new AsyncCallback(CallBackMethod), state);

  if (TimeoutObject.WaitOne(Timeout, false)) 
      { 
       if (IsConnected) 
        return true; 
       else 
        return false; 
      } 
      else 
      { 
       return false; 
      } 

     } 
     catch (Exception Ex) 
     { 
      SocketException = Ex; 
     } 

     return false; 
    } 

    private void CallBackMethod(IAsyncResult AsyncResult) 
    { 
     try 
     { 
      IsConnected = false; 

      if (Socket.Connected) 
      { 
       IsConnected = true; 
      } 
     } 
     catch (Exception Ex) 
     { 
      IsConnected = false; 
      SocketException = Ex; 
     } 
     finally 
     { 
      TimeoutObject.Set(); 
     } 
    } 



    public void Receive(byte[] buffer, int offset, int size, int timeout) 
    { 
     SocketException = null; 
     int startTick = Environment.TickCount; 
     int received = 0; 

     do 
     { 
      if (Environment.TickCount > startTick + timeout) 
      { 
       SocketException = new Exception("Timeout."); 
       return; 
      } 

      try 
      { 
       received += Socket.Receive(buffer, offset + received, size - received, SocketFlags.None); 
      } 
      catch (SocketException Ex) 
      { 
       if (Ex.SocketErrorCode == SocketError.WouldBlock || 
        Ex.SocketErrorCode == SocketError.IOPending || 
        Ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable) 
       { 
        Thread.Sleep(30); 
       } 
       else 
       { 
        SocketException = Ex; 
        return; 
       } 
      } 
     } while (received < size); 
    } 

我不知道我要去哪裏錯了,任何幫助,將不勝感激..

+0

你確定服務器正在監聽嗎?套接字初始化代碼是什麼樣的? – kolosy

+0

是的。我正在模擬一個登錄服務器的啓動器,它可以與舊啓動器一起工作。我知道我的數據包是正確的,套接字是異步初始化的,這可能是一個問題嗎? –

+0

你是什麼意思的異步初始化?這可能是一個問題,是的。 – kolosy

回答

0

Socket.Receive()是一個阻塞調用。如果沒有可用數據,它將阻塞,直到有數據可供讀取。見MSDN

If no data is available for reading, the Receive method will block until data is available, unless a time-out value was set by using Socket.ReceiveTimeout. If the time-out value was exceeded, the Receive call will throw a SocketException.