gpt4 book ai didi

c# - C#异步套接字不会返回整页

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

这是我的创建套接字部分:

_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_client.BeginConnect(_IPEnd, new AsyncCallback(ConnectCallback), _client);
connectDone.WaitOne();
Send(_client, "GET / HTTP/1.1\r\nHost: www.google.de\r\nConnection: Keep-Alive\r\n\r\n");

接收部分:
private void Receive()
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = _client;

// Begin receiving the data from the remote device.
_client.BeginReceive(state.buffer, 0, state.buffer.Length , 0, new AsyncCallback(ReceiveCallback), state);
}

private void ReceiveCallback(IAsyncResult ar)
{
// 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));

client.BeginReceive(state.buffer,0,state.buffer.Length, 0, new AsyncCallback(ReceiveCallback), state);
}
else
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
int length = state.sb.ToString().Length;
ProcessData(state.sb.ToString());

receiveDone.Set();
}

}

缓冲区
    public class StateObject
{
private Guid ID = Guid.NewGuid();
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 4096;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];

public StringBuilder sb = new StringBuilder();
}

为什么此代码不返回整页?

recvcallback的这部分有什么问题吗
if (bytesRead > 0)

最佳答案

您似乎在假定仅当缓冲区已满或连接已关闭时才回叫您。事实并非如此。您可能有一个8K的缓冲区,并且从服务器发送了20K的数据,在10个调用中,每个读取为2K。

假设您要读取直到关闭连接为止,您应该继续进行直到client.EndReceive返回0。(对于具有keepalive的HTTP,您需要读取内容长度并继续进行,直到读取了体内的大量数据为止。 )

编辑:我刚刚看到您在连接上设置了Keep-Alive。如果您希望服务器关闭连接以告诉您它已完成,请不要这样做!

(当然,总的来说,最好使用HTTP库来完成所有这些工作-为什么要编写自己的HTTP处理代码?)

关于c# - C#异步套接字不会返回整页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6926945/

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