我有一个Windows Phone 8应用程序通过套接字与服务器通信 . 服务器很简单 . 它接受一个字符串,返回一个字符串,并立即关闭连接 . 我使用Windows Forms应用程序与服务器通信,从未出现过问题 .
我正在使用下面的代码,我从这个MSDN页面改编,它显示了如何在Windows Phone 8应用程序中使用套接字:
我使用async / await将代码修改为非阻塞 . 所有方法现在都在等待,并且在每个套接字异步操作之后的WaitOne()调用被分离为新任务 . 我没有收到任何套接字错误或异常 . 但是,当ReceiveAsync()调用的匿名Completed事件处理程序触发时,传输的字节值始终为0 .
奇怪的是 . 如果我在ReceiveAsync()的已完成事件处理程序中的某些行上设置断点,则调用超时 . 这不会设置断点,它只发生在某些行上 . 我不知道为什么 . 如果我没有设置断点,则不会发生超时
我究竟做错了什么?这里's the code I'米使用 . 调用代码(未显示)只是创建一个SocketDetails类的实例,然后按顺序调用,等待ConnectAsync(),等待SendAsync("somestring"),最后等待SocketDetails实例上的ReceiveAsync():
///
/// Details object that holds a socket.
///
public class SocketDetails
{
///
/// Creates a new socket details object.
///
/// The host name for the connection.
/// The port name for the connection.
/// The maximum number of milliseconds to wait for a connection before
/// timing out.
/// The maximum number of bytes for the buffer that receives the
/// connection result string.
public SocketDetails(
string hostName,
int portNumber,
int timeOutMS,
int defaultBufferSize)
{
if (String.IsNullOrWhiteSpace(hostName))
throw new ArgumentNullException("The host name is empty.");
if (portNumber <= 0)
throw new ArgumentOutOfRangeException("The port number is less than or equal to 0.");
if (timeOutMS < 0)
throw new ArgumentOutOfRangeException("The time-out value is negative.");
this.HostName = hostName;
this.PortNumber = portNumber;
this.TimeOutMS = timeOutMS;
// Create DnsEndPoint. The hostName and port are passed in to this method.
this.HostEntry = new DnsEndPoint(this.HostName, this.PortNumb