
June 7th, 2003, 02:14 AM
|
|
Junior Member
|
|
Join Date: Jun 2003
Posts: 2
Time spent in forums: < 1 sec
Reputation Power: 0
|
|
C# Reading From Socket Problem/Question
Hi guys/gals. I'm trying to figure out (in C# .NET environment) how to determine when the remote endpoint of a socket is closed. I know that for HTTP, when you send an HTTP/1.0 request, or a HTTP/1.1 request with a "Connection: close" header(like I am), the server is supposed to terminate the connection once it's sent its data. I'm basically trying to port a Proxy server from one I wrote in java to C#. So the general scheme is as follows (pseudocode).
Code:
Socket clientSocket; //passed in from TcpListener
//read request from client socket
byte[] ByteArray = new Byte[this.clientSocket.Available];
int bytes = this.clientSocket.Receive(ByteArray);
//package it nicely in a HTTPRequest class that I made
HTTPRequest hr = new HTTPRequest(ByteArray);
//Get the remote host (server) and connect
IPHostEntry IPHost = Dns.Resolve(hr.getHost());
IPAddress[] address = IPHost.AddressList;
IPEndPoint sEndpoint = new IPEndPoint(address[0], hr.getPort());
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
serverSocket.Connect(sEndpoint);
//send the request
serverSocket.Send(hr.toBytes());
//get the response
/*How do I know when all of the bytes from the server are here?
If I use serverSocket.Available most of the time I don't have any
bytes available yet. I want to read (or block even) until the full
response is available or the remote endpoint is closed. I can
arbitrarily sleep the Thread, but that's a bad hack. I can parse
bytes on the fly and look for a Content-Length header, but I'd
rather not because of complexity of the different encodings etc..
I'd like to know how many bytes are possible to read so that I
can construct the byte[] to read into accordingly like below, or be
able to block until the remote side is done sending.*/
while(?remote_not_done_sending?)
{
Thread.Sleep(some_short_time);
}
byte [] response_buffer = new byte[serverSocket.Available];
Thanks in advance,
Paul
Last edited by tex_guy : June 7th, 2003 at 02:23 AM.
|