예제 #1
0
        /// <summary>
        /// Runs the web server
        /// </summary>
        /// <param name="port">The port number to be used, the default port for HTTP is 80</param>
        /// <param name="address">A specified ip address</param>
        /// <param name="callback">The callback function to read the request and modify the response</param>
        public void RunServer(int port, IPAddress address, OnRecieveRequest callback)
        {
            //begin listening
            server = new TcpListener(address, port);

            server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);

            server.Start();

            //begin accepting
            while (true)
            {
                mre.Reset();

                //on accept, begin reading response
                server.BeginAcceptTcpClient((ac1) =>
                {
                    //once a client connects, unblock to recieve other responses
                    mre.Set();
                    TcpClient client = ((TcpListener)(ac1.AsyncState)).EndAcceptTcpClient(ac1);

                    NetworkStream stream = client.GetStream();

                    //to hold our request
                    byte[] buffer = new byte[WinServer.BUFFER_SIZE];

                    stream.BeginRead(buffer, 0, WinServer.BUFFER_SIZE, (ac2) =>
                    {
                        int bytes_read = stream.EndRead(ac2);

                        string req_str = UnicodeEncoding.ASCII.GetString(buffer, 0, bytes_read);

                        HttpResponse res = new HttpResponse();

                        //invoke the callback method in order to read the request and build the response
                        callback(new HttpRequest(req_str), res);

                        //begin sending response;

                        byte[] resbytes = UnicodeEncoding.ASCII.GetBytes(res.ToString());

                        //send the built response to the client
                        stream.BeginWrite(resbytes, 0, resbytes.Length, (ac3) =>
                        {
                            stream.EndWrite(ac3);

                            //close everything once the response is sent
                            stream.Close();

                            client.Close();

                            //looks like callback hell
                        }, stream);
                    }, stream);
                }, server);

                //block and wait for the next response
                mre.WaitOne();
            }
        }
예제 #2
0
 /// <summary>
 /// Runs the web server
 /// </summary>
 /// <param name="port">The port number to be used, the default port for HTTP is 80</param>
 /// <param name="callback">The callback function to read the request and modify the response</param>
 public void RunServer(int port, OnRecieveRequest callback)
 {
     //calls the main 'RunServer' method
     this.RunServer(port, IPAddress.Any, callback);
 }