我正在使用套接字构建自定义HTTP-Request类。我的代码基于异步套接字的MSDN-Guid,但不幸的是它不起作用。请求运行良好,但我没有收到完整的回复。也许有人可以帮我解决这个问题吗? 这是我的代码:
private void BeginConnect()
{
//Connect To Server
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.BeginConnect(this.ResolveUrl(_requestUri), new AsyncCallback(this.ConnectCallback), socket);
}
private void ConnectCallback(IAsyncResult ar)
{
//Get Socket
Socket socket = (Socket)ar.AsyncState;
//Complete Connection
socket.EndConnect(ar);
//Send HTTP Request
byte[] requestBytes = this.CreateRequest();
socket.BeginSend(requestBytes, 0, requestBytes.Length, SocketFlags.None, new AsyncCallback(this.SendCallback), socket);
}
private void SendCallback(IAsyncResult ar)
{
//Get Socket
Socket socket = (Socket)ar.AsyncState;
//Complete Sending
socket.EndSend(ar);
// Create the state object.
StateObject state = new StateObject();
state.WorkSocket = socket;
//Recieve Response
socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(this.ReceiveCallback), state);
}
private void ReceiveCallback(IAsyncResult ar)
{
//Get StateObject
StateObject state = (StateObject)ar.AsyncState;
Socket socket = state.WorkSocket;
//Complete Receiving
int bytesRead = socket.EndReceive(ar);
if (bytesRead > 0)
{
//Save Already Received Data
state.ResponseBuilder.Append(Encoding.ASCII.GetString(state.Buffer, 0, bytesRead));
//Get Rest Of The Data.
socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(this.ReceiveCallback), state);
}
else
{
if (state.ResponseBuilder.Length > 1)
{
//Shutdown Socket
socket.BeginDisconnect(false, new AsyncCallback(this.DisconnectCallback), state);
//Invoke Callback
SocketResponse resp = new SocketResponse(state.ResponseBuilder.ToString(), HttpStatusCode.Accepted); //TODO
_callback.Invoke(resp);
}
}
}
private void DisconnectCallback(IAsyncResult ar)
{
//Get Socket
StateObject state = (StateObject)ar.AsyncState;
Socket socket = state.WorkSocket;
//Shutdown Socket
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
答案 0 :(得分:0)
TCP连接是基于流的。您每次可以读取的数据量涉及随机元素,您需要循环读取,直到您拥有整个消息。
如果您以前没有网络经验,那么实施套接字是一项容易出错的练习。说过所有这些问题都已在开源网络通信库networkComms.net中得到解决。如果您按照最基本的11行示例here,一直到调用树,您将看到如何正确实现异步套接字。