2012-01-23 82 views
1

我是WP7和Socket編程的新手。我已經通過msdn示例代碼http://msdn.microsoft.com/en-us/library/hh202864(v=VS.92).aspx#Y4537並經過測試使用。發送工作正常,但無法接收,這是我用於接收udp數據包數據的代碼。UDP套接字接收在wp7中失敗

在此我斷點@if (e.SocketError == SocketError.Success)

public string Receive(int portNumber) 
    { 
     string response = "Operation Timeout"; 

     // We are receiving over an established socket connection 
     if (_socket != null) 
     { 
      // Create SocketAsyncEventArgs context object 
      SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs(); 
      socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, portNumber); 

      // Setup the buffer to receive the data 
      socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE); 

      // Inline event handler for the Completed event. 
      // Note: This even handler was implemented inline in order to make this method self-contained. 
      socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) 
      { 
       try 
       { 
        if (e.SocketError == SocketError.Success) 
        { 
         // Retrieve the data from the buffer 
         response = Encoding.UTF8.GetString(e.Buffer, e.Offset,e.BytesTransferred); 
         response = response.Trim('\0'); 
        } 
        else 
        { 
         response = e.SocketError.ToString(); 
        } 
        _clientDone.Set(); 
       } 
       catch (Exception ex) 
       { 
        ex.ToString(); 
       } 

      }); 

      // Sets the state of the event to nonsignaled, causing threads to block 
      _clientDone.Reset(); 

      // Make an asynchronous Receive request over the socket 
      _socket.ReceiveFromAsync(socketEventArg); 


      // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds. 
      // If no response comes back within this time then proceed 
      _clientDone.WaitOne(TIMEOUT_MILLISECONDS); 
     } 
     else 
     { 
      response = "Socket is not initialized"; 
     } 

     return response; 
    } 

回答

0

您是否嘗試過使用WP7/Silverlight中的特定UDP支持總是失敗?根據您的場景和要求使用UdpSingleSourceMulticastClientUdpAnySourceMulticastClient。這裏是關於在Silverlight的UDP的介紹文章@Working with Multicast

+0

:你可以給任何工作示例的UDP接收? –

+0

不可以。根據您要完成的內容,有許多Silverlight 4博客文章解釋了使用剛剛提到的兩個類的UDP實現的更多細節。 – JustinAngel