我是WP7和Socket编程的新手。我已经通过msdn示例代码http://msdn.microsoft.com/en-us/library/hh202864(v=VS.92).aspx#Y4537并进行了测试以供使用。发送工作正常,但无法接收,这是我用于接收udp数据包数据的代码。
在此我的断点总是失败@ 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 :(得分:0)
您是否尝试过在WP7 / Silverlight中使用特定的UDP支持?根据您的方案和要求,使用UdpSingleSourceMulticastClient或UdpAnySourceMulticastClient。这是关于Silverlight @ Working with Multicast
中的UDP的介绍文章