المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Problem reconnecting using Socket class



C# Programming
03-29-2009, 12:11 AM
I am trying write a TCP client that connects to a server and requests HTTP packets using the Socket class. The problem I'm having is when I receive a HTTP return code of 400 (Bad Request), the server disconnects me and I have to close my connection as well. Once I close my connection, the Socket class won't let me start another TCP handshake, let alone send any more packets.

Here is my code for the connection:

;
Socket socket;
IPEndPoint hostEndPoint;
string packet;

public void run()
{
TCPConnect();

packet = SendReceive("/signin.aspx", "GET");
if (GetReturnCode(packet) == "400")
TCPReset();

packet = SendReceive("/index.html", "GET");

TCPClose();
}

private void TCPConnect()
{
// Make sure there is a connection
if (socket == null)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
hostEndPoint = new IPEndPoint(ipaddr, port);
}

socket.Connect(hostEndPoint);
}

// My problem is getting this function working properly
private void TCPReset()
{
socket.Disconnect(true); // Close the socket connection and allow reuse of the socket
socket.Connect(hostEndPoint); // This is ignored according to Ethereal,
// nothing is sent even using socket.Send()
}

private void TCPClose()
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}

private string SendReceive(string strURI, strMethod)
{
string pcAppend = " HTTP/1.1\r\nConnection: Keep-Alive\r\n\Content-Length: 0\r\n" +
"User-Agent: Mozilla/4.0 (Compatible; MSIE 7.0; Windows NT 5.2; .NET CLR " +
"2.0.50727; .NET CLR 3.0.04506.30; InfoPath.1; .NET CLR 3.5.21022)\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\nHost: " + strIPAddress + "\r\n\r\n";
byte[] pcSend = System.Text.ASCIIEncoding.ASCII.GetBytes(strMethod + strURI + pcAppend);
byte[] bfBuffer = new byte[10240];

socket.Send(pcSend, pcSend.Length, 0);
socket.Receive(bfBuffer, bfBuffer.Length, SocketFlags.None);

return System.Text.ASCIIEncoding.ASCII.GetString(bfBuffer);
}
;

I've been monitoring the commuications with Ethereal. .Net is closing the connection just fine, but it ignores any socket.Connect() calls after the initial connection.

Any ideas?