c# - 为什么我在此示例中通过套接字传输数据时丢失了字节?
问题描述
我正在尝试异步接收数据并将其存储到 StringBuilder 中,当 StringBuilder 长度大于 1000 时处理此数据。每次我调用我的 Update_Interface 函数时,都会丢失一些数据。我将缓冲区大小设置为 256。我该如何解决这个问题?这是因为我的功能需要一些时间来处理我的数据,然后客户端没有接收数据?
public 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());
}
}
public void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous 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.ASCII.GetString(state.buffer, 0, bytesRead));
if (state.sb.Length > 1000)
{
Update_Interface(state.sb.ToString());
state.sb.Clear();
}
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
receiveDone.Set();
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
解决方案
推荐阅读
- python - 在 Python 中创建列表列表
- regex - nifi routeText 处理器使用问题
- c++ - 期望一个类型,得到一个模板
- python-2.7 - 通过 python 执行 PowerShell 脚本
- redis - Google Cloud - 用于管理队列的 Redis 替代方案?
- c# - 用 TextBox 中的值填充 DropBox
- google-cloud-dataflow - Apache Beam 如何处理多个窗口
- vue.js - 将 vue-router 组件解释为函数
- python-2.7 - 试图将文件与字典进行比较 python 2.7 无输出
- c# - 跳过“添加状态”,直接进入“编辑状态”