java socket异步接收数据_调用socket的ReceiveAsync()调用后,接收的数据缓冲区总是为空?...

我有一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值