Exemple #1
0
    public static void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        StateObject state   = (StateObject)ar.AsyncState;
        Socket      handler = state.workSocket;

        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(
                                state.buffer, 0, bytesRead));

            content = state.sb.ToString();

            HTTPHeaders header = new HTTPHeaders();

            if (content.IndexOf((char)13) > -1)
            {
                if (state.sb.ToString().StartsWith("GET /"))
                {
                    string          getPath  = content.ToString().Split(' ')[1].Replace('/', '\\');
                    string          pathDest = path + getPath;
                    FileHandleClass fH       = new FileHandleClass(pathDest);
                    if (fH.FileExists())
                    {
                        byte[] fileData   = fH.GetFileBytes();
                        byte[] headerData = System.Text.Encoding.UTF8.GetBytes(header.HeaderSuccess(fileData.Length));
                        byte[] allData    = new byte[fileData.Length + headerData.Length + 2];
                        Array.Copy(headerData, allData, headerData.Length);
                        Array.Copy(fileData, 0, allData, headerData.Length, fileData.Length);
                        allData[allData.Length - 2] = 13;
                        allData[allData.Length - 1] = 10;
                        content = header.HeaderSuccess(fileData.Length);
                        Send(handler, allData);
                    }
                    else
                    {
                        content = header.HeaderNotFound();
                        Send(handler, content);
                    }
                }
                else
                {
                    content = header.HeaderBadRequest();
                    Send(handler, content);
                }

                Console.WriteLine("Read {0} bytes. \n Data : {1}",
                                  content.Length, content);
            }
            else
            {
                content = header.HeaderBadRequest();
                Send(handler, content);
            }
        }
    }