gpt4 book ai didi

C# 套接字接收 : Taking in data until buffer is full dilemma

转载 作者:行者123 更新时间:2023-12-03 11:53:57 24 4
gpt4 key购买 nike

这是我遇到问题的代码:

// read the file in chunks of 5KB
var buffer = new byte[1024*5];
int bytesRead = 0;
do
{
bytesRead = host.Receive(buffer, buffer.Length, 0);
output.Write(buffer, 0, bytesRead);
}
while (bytesRead == buffer.Length);

所以这是我的问题:只要缓冲区已满,我就想读入数据。但是,即使有更多数据,发送时也不能保证缓冲区被填满。这会导致 Receive 过早退出。如果我将 while 条件更改为 bytesRead > 0然后它到达数据和接收 block 的末尾,直到有更多数据可用(它不会)。我该如何解决这个问题?

最佳答案

我认为您需要考虑协议(protocol)的工作原理并制定更强大的解决方案。要么你去阻塞,然后你要么等到你没有更多的数据要读取,然后做其他事情,当你知道你有更多的数据要读取时再次读取。

或者你添加线程并有一个单独的线程,它只是读取然后它是否阻塞并不重要,因为它将在一个单独的线程上。

另一种可能更简单的解决方案是使用异步读取。

您可以在此处阅读更多信息:https://msdn.microsoft.com/en-us/library/bbx2eya8(v=vs.110).aspx

上面网站的一个简单示例是从阅读开始:

private 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) {
Console.WriteLine(e.ToString());
}
}

然后当有数据需要处理时,你会得到一个回调到 ReceiveCallback:
private static 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));
// 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 (state.sb.Length > 1) {
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

如果不是我们需要更多地了解您使用的协议(protocol)以及您是否出于某种原因需要阻止读取,我希望这可以工作,以便我们可以提供更具体的信息和帮助。

关于C# 套接字接收 : Taking in data until buffer is full dilemma,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36880293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com