Domanda

The .NET has a built in HttpListener class, however I was wondering how I could roll my own Http Listener. I know there are a lot of implications to this, but I just want see the browser and my own app interact with each other.

This is the code I have written so far:

Socket servSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
servSocket.ExclusiveAddressUse = false; // Does this matter?
servSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
servSocket.Listen(10);

byte[] buffer;

do
{
    try
    {
        Socket clientSocket = servSocket.Accept();

        Console.WriteLine("Received Request at: {0}.", DateTime.Now);

        EndPoint remoteEP = clientSocket.RemoteEndPoint;
        buffer = new byte[1024];
        clientSocket.ReceiveFrom(buffer, SocketFlags.None, ref remoteEP);
        string request = Encoding.UTF8.GetString(buffer);
        System.Diagnostics.Trace.Write(request);
        buffer = Encoding.UTF8.GetBytes("<html><head><link rel=\"icon\" href=\"data:;base64,=\"></head><body></body></html>");
        clientSocket.Send(buffer);

        clientSocket.Close();
        clientSocket.Dispose();
    }
    catch { }
}
while (this.isRunning);

This sort of works, however two issues I have noted, is that the clientSocket local end-point is on the same port as the servSocket. With the built-in HttpListener, the request gets handled by a random local end-point port. How can I mimic this?

I have set the ExclusiveAddressUse flag to false, however I still cannot bind more than one socket to that particular end-point, so what is its exact use?

Furthermore, from time to time I get a SocketException with 'An established connection was aborted by the software in your host machine'. What could be the source of the problem?

È stato utile?

Soluzione

The simple answer is "you don't really care about that".

TCP works by estabilishing a two-way "virtual" persistent connection. To achieve this illusion, it uses a separate port for communication with a given client. You still connect to port 80 (for example), but a thousand clients use a thousand different ports for the actual communication with the server.

ExclusiveAddressUse allows you to bind more sockets to the same port - but each has to have its own IP address.

Networking is hard. Us as high an abstraction as you can, be it TcpListener, HttpListener or even OWIN.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top