socket 异步接收的问题

clickchen2003 2003-07-24 04:52:37
//以下的程序是msdn上的关于socket异步接收的例子(socket --异步客户端套接字), 我在调试的过程中 怎么发现ReceiveCallback里面的一个if语句从来都没有执行过(他下面的那句执行了),不知所以, 哪位高手可以帮我解释一下


public class StateObject
{
public Socket workSocket = null; // Client socket.
public const int BufferSize = 76; // Size of receive buffer.
public byte[] buffer = new byte[BufferSize]; // Receive buffer.
public StringBuilder sb = new StringBuilder();// Received data string.
}

public static void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;

// Begin receiving the data from the remote device.
client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}

private static void ReceiveCallback( IAsyncResult ar )
{
try
{
// Retrieve the state object and the client socket
// from the async state object.

StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.Default.GetString(state.buffer,0,bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
//这个if语句似乎从来都没有执行
if(state.sb.Length > 1)
{
response = state.sb.ToString();
MessageBox.Show(response);
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
...全文
69 3 打赏 收藏 举报
写回复
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xixigongzhu 2003-07-25
  • 打赏
  • 举报
回复
你在三个分支的前面各自加个打印语句,把条件打印出来,先测试一下程序运行的路径。
clickchen2003 2003-07-25
  • 打赏
  • 举报
回复
是if(state.sb.Length > 1)这个判断都没有执行?
ptxq 2003-07-24
  • 打赏
  • 举报
回复
if语句主要判断有没有节收到数据,然后进行处理。如果没有数据收到,自然不会执行了。
相关推荐
发帖
C#

10.8w+

社区成员

.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
帖子事件
创建了帖子
2003-07-24 04:52
社区公告

让您成为最强悍的C#开发者