Пример #1
0
        public void readHeaders()
        {
            Console.WriteLine("readHeaders()");
            String line;

            while ((line = streamReadLine()) != null)
            {
                if (line.Equals(""))
                {
                    ServerLog.LogInfo("got headers");
                    return;
                }

                int separator = line.IndexOf(':');
                if (separator == -1)
                {
                    throw new Exception("invalid http header line: " + line);
                }
                String name = line.Substring(0, separator);
                int    pos  = separator + 1;
                while ((pos < line.Length) && (line[pos] == ' '))
                {
                    pos++;                     // strip any spaces
                }

                string value = line.Substring(pos, line.Length - pos);
                ServerLog.LogInfo(String.Format("header: {0}:{1}", name, value));
                httpHeaders[name] = value;
            }
        }
Пример #2
0
        public void handlePOSTRequest()
        {
            // this post data processing just reads everything into a memory stream.
            // this is fine for smallish things, but for large stuff we should really
            // hand an input stream to the request processor. However, the input stream
            // we hand him needs to let him see the "end of the stream" at this content
            // length, because otherwise he won't know when he's seen it all!

            ServerLog.LogInfo("get post data start");
            int          content_len = 0;
            MemoryStream ms          = new MemoryStream();

            if (this.httpHeaders.ContainsKey("Content-Length"))
            {
                content_len = Convert.ToInt32(this.httpHeaders["Content-Length"]);
                if (content_len > MAX_POST_SIZE)
                {
                    throw new Exception(
                              String.Format("POST Content-Length({0}) too big for this simple server",
                                            content_len));
                }
                byte[] buf     = new byte[BUF_SIZE];
                int    to_read = content_len;
                while (to_read > 0)
                {
                    ServerLog.LogInfo(String.Format("starting Read, to_read={0}", to_read));

                    int numread = this.inputStream.Read(buf, 0, Math.Min(BUF_SIZE, to_read));
                    ServerLog.LogInfo(String.Format("read finished, numread={0}", numread));
                    if (numread == 0)
                    {
                        if (to_read == 0)
                        {
                            break;
                        }
                        else
                        {
                            throw new Exception("client disconnected during post");
                        }
                    }
                    to_read -= numread;
                    ms.Write(buf, 0, numread);
                }
                ms.Seek(0, SeekOrigin.Begin);
            }
            ServerLog.LogInfo("get post data end");
            srv.handlePOSTRequest(this, new StreamReader(ms));
        }
Пример #3
0
        public void parseRequest()
        {
            String request = streamReadLine();

            if (request == null)
            {
                // Connection closed by browser
                throw new EndOfStreamException("EOS_BROWSER");
            }
            string[] tokens = request.Split(' ');
            if (tokens.Length != 3)
            {
                throw new Exception("invalid http request line");
            }
            http_method = tokens[0].ToUpper();
            http_url    = tokens[1];
            http_protocol_versionstring = tokens[2];

            ServerLog.LogInfo("starting: " + request);
        }
Пример #4
0
 public void listen()
 {
     try{
         listener = new TcpListener(address, port);
         listener.Start();
         while (is_active)
         {
             ServerLog.LogInfo("Listening!");
             TcpClient s = listener.AcceptTcpClient();
             ServerLog.LogInfo("Client accepted!");
             s.ReceiveTimeout = 1000;                    // After 1 seconds, time out the read operation!!!
             // Why? Because as long as the operation is waiting, this thread is in "native code" and Unity cannot go to "play" mode or reload the scripts!
             HttpProcessor processor = new HttpProcessor(s, this);
             Thread        thread    = new Thread(new ThreadStart(processor.process));
             thread.Start();
             Thread.Sleep(1);
         }
     } catch (Exception e) {
         ServerLog.Log("Server Listening Exception!");
         ServerLog.Log(e);
     }
 }
Пример #5
0
        /// <summary>
        /// HTTP GET => Implement to load actual files from the server... Returns the html/js/css/... files.
        /// </summary>
        /// <param name="p">P.</param>
        public override void handleGETRequest(HttpProcessor p)
        {
            String requestedUrl = p.http_url;

            ServerLog.Log(String.Format("request: {0}", requestedUrl));

            if (requestedUrl.EndsWith("/"))
            {
                // We are looking in a directory...
            }

            //Extract the requested file name
            String directory = requestedUrl.Substring(requestedUrl.IndexOf("/"), requestedUrl.LastIndexOf("/") - requestedUrl.IndexOf("/"));
            String filename  = requestedUrl.Substring(requestedUrl.LastIndexOf("/") + 1);

            /////////////////////////////////////////////////////////////////////
            // Identify the Physical Directory
            /////////////////////////////////////////////////////////////////////
            String physicalDirectory = config.GetPhysicalPath(directory);

            // TODO: check if directory exists...

            /////////////////////////////////////////////////////////////////////
            // Identify the File Name
            /////////////////////////////////////////////////////////////////////

            //If The file name is not supplied then look in the default file list
            if (filename.Length == 0)
            {
                // Get the default filename
                filename = config.GetDefaultFileInFolder(physicalDirectory);
            }

            // TODO: check if filename is no longer "" and check if file exists...

            String mimeHeader = config.GetMimeType(filename);

            String fullPath = Path.Combine(physicalDirectory, filename);

            ServerLog.LogInfo(" < " + fullPath);

            if (!File.Exists(fullPath))
            {
                ServerLog.Log("    [!]" + ServerHttpStatusCode.ERR_404_FILENOTFOUND);
                String errorMessage = "<H2>404 Error! File Does Not Exists...</H2>";
                SendHeader(config.DefaultMime, errorMessage.Length, ServerHttpStatusCode.ERR_404_FILENOTFOUND, p);
                p.outputStream.Write(errorMessage);
            }
            else
            {
                ServerLog.LogInfo("    [+]" + HttpStatusCode.OK);
                FileInfo f           = new FileInfo(fullPath);
                Stream   filecontent = new BufferedStream(f.OpenRead());
                try{
                    SendHeader(mimeHeader, f.Length, ServerHttpStatusCode.OK, p);
                    p.outputStream.Flush();
                    CopyStream(filecontent, p.socket.GetStream());
                }finally{
                    filecontent.Close();
                }
            }
        }