static bool ReadStreamTests() { Console.WriteLine("\nTesting Read Functionality:"); Console.Write("\tTesting reading all content from both streams (FileStream, FileStream): "); FileStream fs1 = new FileStream("testFile1.txt", FileMode.Open, FileAccess.Read); byte[] buffer1 = new byte[fs1.Length]; int bytesRead = fs1.Read(buffer1, 0, buffer1.Length); string msg1 = System.Text.Encoding.ASCII.GetString(buffer1, 0, bytesRead); FileStream fs2 = new FileStream("testFile1.txt", FileMode.Open, FileAccess.Read); byte[] buffer2 = new byte[fs2.Length]; bytesRead = fs2.Read(buffer2, 0, buffer2.Length); string msg2 = System.Text.Encoding.ASCII.GetString(buffer2, 0, bytesRead); ConcatStream cs1 = new ConcatStream(fs1, fs2); byte[] buffer3 = new byte[cs1.Length]; bytesRead = cs1.Read(buffer3, 0, buffer3.Length); string msg3 = System.Text.Encoding.ASCII.GetString(buffer3, 0, bytesRead); if (msg3 != msg1 + msg2 || msg3.Length <= 0 || msg2.Length <= 0 || msg1.Length <= 0) { Console.WriteLine("FAILED"); } else { Console.WriteLine("SUCCESS"); } cs1.Close(); /***************************************/ Console.Write("\tTesting reading all content from both streams, random amounts (MemoryStream, MemoryStream): "); MemoryStream ms1 = new MemoryStream(buffer1); MemoryStream ms2 = new MemoryStream(buffer2); cs1 = new ConcatStream(ms1, ms2); byte[] buffer4 = new byte[cs1.Length]; Random rnd = new Random(); msg3 = ""; bytesRead = 0; int totalRead = 0; bytesRead = cs1.Read(buffer4, 0, rnd.Next(1, buffer4.Length - totalRead)); msg3 += System.Text.Encoding.ASCII.GetString(buffer4, 0, bytesRead); totalRead += bytesRead; while (bytesRead != 0) { int max = Math.Max(buffer4.Length - totalRead, 1); bytesRead = cs1.Read(buffer4, 0, rnd.Next(1, max)); msg3 += System.Text.Encoding.ASCII.GetString(buffer4, 0, bytesRead); buffer4 = new byte[cs1.Length]; totalRead += bytesRead; } if (msg3 == msg1 + msg2 && msg3.Length > 0 && msg2.Length > 0 && msg1.Length > 0) { Console.WriteLine("SUCCESS"); } else { Console.WriteLine("FAILED"); } ms1.Close(); ms2.Close(); cs1.Close(); /*****************************/ Console.Write("\tTesting read all from (memoryStream,NoSeekMemoryStream): "); ms1 = new MemoryStream(buffer1); ms2 = new NoSeekMemoryStream(buffer2); cs1 = new ConcatStream(ms1, ms2); msg1 = System.Text.Encoding.ASCII.GetString(buffer1, 0, buffer1.Length); msg2 = System.Text.Encoding.ASCII.GetString(buffer2, 0, buffer2.Length); buffer3 = new byte[cs1.Length]; bytesRead = cs1.Read(buffer3, 0, buffer3.Length); msg3 = System.Text.Encoding.ASCII.GetString(buffer3, 0, buffer3.Length); if (msg3 == msg1 + msg2 && msg3.Length > 0 && msg2.Length > 0 && msg1.Length > 0) { Console.WriteLine("SUCCESS"); } else { Console.WriteLine("FAILED"); } /*********************************/ Console.Write("\tTesting if position resets when stream is passed to CS: "); fs1 = new FileStream("testFile1.txt", FileMode.Open, FileAccess.Read); int amountToRead = 10; buffer1 = new byte[amountToRead]; bytesRead = fs1.Read(buffer1, 0, buffer1.Length); msg1 = System.Text.Encoding.ASCII.GetString(buffer1, 0, bytesRead); fs2 = new FileStream("testFile1.txt", FileMode.Open, FileAccess.Read); buffer2 = new byte[amountToRead]; bytesRead = fs2.Read(buffer2, 0, buffer2.Length); msg2 = System.Text.Encoding.ASCII.GetString(buffer2, 0, bytesRead); cs1 = new ConcatStream(fs1, fs2); buffer3 = new byte[amountToRead]; bytesRead = cs1.Read(buffer3, 0, buffer3.Length); msg3 = System.Text.Encoding.ASCII.GetString(buffer3, 0, bytesRead); if (msg3 != msg1 || msg3 != msg2 || msg3.Length <= 0) { Console.WriteLine("FAILED"); } else { Console.WriteLine("SUCCESS"); } fs1.Close(); fs2.Close(); cs1.Close(); /*********************************************************************/ Console.Write("\tTesting reading from stream no length property (FileStream, NetworkStream): "); string urlAddress = "https://www.facebook.com"; HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(urlAddress); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); fs2 = new FileStream("testFile2.txt", FileMode.Open, FileAccess.Read); byte[] buffer = new byte[fs2.Length + 2]; if (response.StatusCode == HttpStatusCode.OK) { Stream receiveStream = response.GetResponseStream(); cs1 = new ConcatStream(fs2, receiveStream); bytesRead = cs1.Read(buffer, 0, buffer.Length); msg1 = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead); if (msg1.Length > fs2.Length + 1) { Console.WriteLine("SUCCESS"); } else { Console.WriteLine("FAILED"); } } else { Console.Write("!!!!!!!!!!!!!!!!!!!SOCKET CONNNECTION FAILED, cannot run test."); throw new ArgumentException(); } fs2.Close(); cs1.Close(); return(true); }
private static WebRequest BuildRequest(TcpClient client) { WebRequest newWebRequest = new WebRequest(client.GetStream()); ConcatStream bodyStream = null; Console.WriteLine("Building Request..."); List <byte> bufferedRequest = new List <byte>(); bool done = false; int length = -1; while (!done) { NetworkStream networkStream = client.GetStream(); int available = client.Available; while (client.Available > 0) { byte[] buf = new byte[client.Available]; networkStream.Read(buf, 0, client.Available); bufferedRequest.AddRange(buf); string request = System.Text.ASCIIEncoding.UTF8.GetString(bufferedRequest.ToArray()); if (!isValidRequest(bufferedRequest)) { client.Close(); //listener.Stop (); return(null); } if (request.Length >= 4 && request.Contains(@"\r\n\r\n")) { Console.WriteLine("breaking inner"); done = true; break; } } var reqString = System.Text.ASCIIEncoding.UTF8.GetString(bufferedRequest.ToArray()); if (length == -1 && reqString.Split(new String[] { CRLF }, StringSplitOptions.None).Length > 2) { //check for content length var headers = parseHeaders(reqString); if (headers.ContainsKey("Content-Length")) { length = int.Parse(headers ["Content-Length"]); } } if (done) { // find part of body that has been read already string reqStr = System.Text.ASCIIEncoding.UTF8.GetString(bufferedRequest.ToArray()); int index = reqStr.IndexOf(@"\r\n\r\n"); var alreadyReadBody = reqStr.Substring(index + @"\r\n\r\n".Count()); Console.WriteLine("Already: {0}", alreadyReadBody); MemoryStream already = new MemoryStream(System.Text.ASCIIEncoding.UTF8.GetBytes(alreadyReadBody)); if (length != -1) { bodyStream = new ConcatStream(already, networkStream, length); } else { bodyStream = new ConcatStream(already, networkStream); } } } // request has been buffered, now build it newWebRequest.Method = "GET"; string requestString = System.Text.ASCIIEncoding.UTF8.GetString(bufferedRequest.ToArray()); newWebRequest.Body = bodyStream; string[] firstLine = requestString.Split(@"\r\n".ToCharArray()) [0].Split(' '); newWebRequest.HTTPVersion = firstLine[2]; newWebRequest.RequestTarget = firstLine [1]; newWebRequest.Headers = parseHeaders(requestString); return(newWebRequest); }
static bool PositionTests() { Console.WriteLine("\nTesting Concat Stream Position Property: "); Console.Write("\tTesting Position after Read (FileStream, FileStream): "); FileStream fs1 = new FileStream("testFile1.txt", FileMode.Open, FileAccess.Read); FileStream fs2 = new FileStream("testFile1.txt", FileMode.Open, FileAccess.Read); ConcatStream cs1 = new ConcatStream(fs1, fs2); long initialPosition = cs1.Position; byte[] buffer1 = new byte[10]; int bytesRead = cs1.Read(buffer1, 0, buffer1.Length); long currentPosition = cs1.Position; if (currentPosition - bytesRead != initialPosition || currentPosition == 0) { Console.WriteLine("FAILED"); } else { Console.WriteLine("SUCCESS"); } fs1.Close(); fs2.Close(); cs1.Close(); /******************************************/ Console.Write("\tTesting Position after Write (FileStream, FileStream): "); FileStream fs3 = new FileStream("testFile3.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); string testString = "Checking"; byte[] toBytes = Encoding.ASCII.GetBytes(testString); fs3.Write(toBytes, 0, toBytes.Length); FileStream fs4 = new FileStream("testFile4.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); ConcatStream cs2 = new ConcatStream(fs3, fs4); initialPosition = cs2.Position; testString = "Testing, 1 2 3, Testing..."; toBytes = Encoding.ASCII.GetBytes(testString); cs2.Write(toBytes, 0, toBytes.Length); currentPosition = cs2.Position; if (currentPosition - toBytes.Length != initialPosition || currentPosition == 0) { Console.WriteLine("FAILED"); } else { Console.WriteLine("SUCCESS"); } fs3.Close(); fs4.Close(); cs2.Close(); /*********************************************/ Console.Write("\tTesting Position after Seek (FileStream, FileStream): "); fs1 = new FileStream("testFile1.txt", FileMode.Open, FileAccess.Read); fs2 = new FileStream("testFile1.txt", FileMode.Open, FileAccess.Read); cs1 = new ConcatStream(fs1, fs2); int offset = 20; cs1.Seek(offset, SeekOrigin.Begin); if (cs1.Position == offset) { Console.WriteLine("SUCCESS"); } else { Console.WriteLine("FAILED"); } fs1.Close(); fs2.Close(); cs1.Close(); /******************************************/ Console.Write("\tTesting set Position after length max (FileStream, FileStream, Length): "); fs1 = new FileStream("testFile1.txt", FileMode.Open, FileAccess.Read); fs2 = new FileStream("testFile1.txt", FileMode.Open, FileAccess.Read); cs1 = new ConcatStream(fs1, fs2, 10); try { cs1.Position = 12; Console.WriteLine("FAILED"); } catch { Console.WriteLine("SUCCESS"); } fs1.Close(); fs2.Close(); cs1.Close(); /******************************************/ Console.Write("\tTesting exception for passing the same instance for both streams (FileStream, FileStream): "); fs3 = new FileStream("testFile10.txt", FileMode.Create, FileAccess.ReadWrite); try { cs2 = new ConcatStream(fs3, fs3); Console.WriteLine("FAILED"); } catch { Console.WriteLine("SUCCESS"); } cs1.Close(); return(true); }
private static WebRequest BuildRequest(TcpClient client) { WebRequest newWebRequest = new WebRequest(client.GetStream()); ConcatStream bodyStream = null; Console.WriteLine("Building Request..."); List <byte> bufferedRequest = new List <byte>(); bool done = false; int length = -1; while (!done) { NetworkStream networkStream = client.GetStream(); lock (networkStream) { networkStream.ReadTimeout = DEFAULT_NETWORK_READ_TIMEOUT; int available = client.Available; var watch = System.Diagnostics.Stopwatch.StartNew(); while (true) { // wait till client is available //while(client.Available != 0){} int bufferSize = 1024; int bytesRead = 0; byte[] buf = new byte[bufferSize]; try{ //Console.WriteLine("Client.available: {0}", client.Available); if (client.Available > 0) { bytesRead = networkStream.Read(buf, 0, buf.Length); } else { //Console.WriteLine("client not avail"); //client.Close (); done = true; //break; } }catch (IOException e) { Console.WriteLine("Timing out: Read timeout"); client.Close(); //listener.Stop (); watch.Stop(); return(null); } //Console.WriteLine ("Bytes Read: {0}", bytesRead); bufferedRequest.AddRange(buf); string request = System.Text.ASCIIEncoding.UTF8.GetString(bufferedRequest.ToArray()); //Console.WriteLine (); //Console.WriteLine ("request:\n{0}", request); //Console.WriteLine (); // check single crlf timeout if (bufferedRequest.Count > FIRST_CRLF_DATA_TIMEOUT && !request.Contains(CRLF)) { //Console.WriteLine ("Timing out: First CRLF not found in first {0} bytes", //bufferedRequest.Count); //time out!! // close socket and return client.Close(); return(null); } //check timeout #2 var elapsedSeconds = watch.ElapsedMilliseconds / 1000.0; // check for double crlf timeouts if (elapsedSeconds >= DOUBLE_CRLF_TIMEOUT || bufferedRequest.Count > DOUBLE_CRLF_DATA_TIMEOUT) { if (!request.Contains(DOUBLE_CRLF)) { if (elapsedSeconds >= DOUBLE_CRLF_TIMEOUT) { Console.WriteLine("Timing out: Double CRLF not found in {0} seconds", elapsedSeconds); } else { Console.WriteLine("Timing out: Double CRLF not found in first {0} bytes", bufferedRequest.Count); } return(null); } } if (bufferedRequest.Count != 0) { //Console.WriteLine ("Count != 0: {0}", bufferedRequest.Count ); if (!isValidRequest(bufferedRequest)) { client.Close(); //listener.Stop (); watch.Stop(); return(null); } if (request.Length >= 4 && request.Contains(DOUBLE_CRLF)) { //Console.WriteLine ("breaking inner"); done = true; break; } } else { //Console.WriteLine ("Count = 0"); } } var reqString = System.Text.ASCIIEncoding.UTF8.GetString(bufferedRequest.ToArray()); if (length == -1 && reqString.Split(new String[] { CRLF }, StringSplitOptions.None).Length > 2) { //check for content length var headers = parseHeaders(reqString); if (headers.ContainsKey("Content-Length")) { length = int.Parse(headers ["Content-Length"]); } } if (done) { if (bufferedRequest.Count <= 0) { return(null); } // find part of body that has been read already string reqStr = System.Text.ASCIIEncoding.UTF8.GetString(bufferedRequest.ToArray()); int index = reqStr.IndexOf(DOUBLE_CRLF); var alreadyReadBody = reqStr.Substring(index + DOUBLE_CRLF.Count()); //Console.WriteLine ("Already: {0}", alreadyReadBody); MemoryStream already = new MemoryStream(System.Text.ASCIIEncoding.UTF8.GetBytes(alreadyReadBody)); if (length != -1) { bodyStream = new ConcatStream(already, networkStream, length); } else { bodyStream = new ConcatStream(already, networkStream); } } } } // request has been buffered, now build it newWebRequest.Method = "GET"; string requestString = System.Text.ASCIIEncoding.UTF8.GetString(bufferedRequest.ToArray()); newWebRequest.Body = bodyStream; string[] firstLine = requestString.Split(CRLF.ToCharArray()) [0].Split(' '); newWebRequest.HTTPVersion = firstLine[2]; newWebRequest.RequestTarget = System.Uri.UnescapeDataString(firstLine [1]);; newWebRequest.Headers = parseHeaders(requestString); return(newWebRequest); }
private static WebRequest BuildRequest(TcpClient client) { Message message = new Message(); WebRequest webRequest = null; //make a 1mb buffer byte[] buffer = new byte[1024]; //stop watch that checks if x seconds have passed var stopWatch = new System.Diagnostics.Stopwatch(); //NOTE: client is closed after null is returned try { NetworkStream stream = client.GetStream(); //NOTE: Must dispose networkstream in webrequest responses. //the read will throw an IOException if it takes 2 seconds //to stream.Read() a megabyte of data stream.ReadTimeout = 2000; webRequest = new WebRequest(stream); //reference the stream so we can write response to it, then close. //read the networkstream's data into buffer //loop to recieve all data sent by the client. int bytesRead = 0; string content = ""; int firstThresholdBytes = 0; int secondThresholdBytes = 0; //we add crlf flag everytime we enter CRLF state //when flag is false, first crlf has not been reached //when it is true, we have reached first crlf, can do checks //then potentially move on to secondThreshold checking bool flag = false; //needs to exit once FinalState which tells us we finished while (!(message.State is FinalState) && stream.DataAvailable) { //starts if first iteration, else resumes. stopWatch.Start(); bytesRead = stream.Read(buffer, 0, buffer.Length); /* * The reason we stop the stop watch after every * Read() is we don't want to include the elapsed * time of functionality that doesn't include * reading from the stream like checking * validity and building the HTTP request object. */ stopWatch.Stop(); /* * If the double line break has not been received * after 10 seconds total, then return null which * will close the connection. * */ if (stopWatch.ElapsedMilliseconds > 10) { return(null); } if (!flag) //haven't reached first line break yet { firstThresholdBytes += bytesRead; } else { secondThresholdBytes += bytesRead; } content = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead); do { content = message.CheckValidity(content, webRequest); if (message.State is ErrorState) { return(null); } if (!flag && message.State is CRLFState) { flag = true; } } while (content != ""); //check if firstThreshold value has been exceeded if (!flag && firstThresholdBytes >= firstThreshold) { return(null); } else if (!(message.State is FinalState) && //final state reprsents all the content being read up until body or double CRLF secondThresholdBytes >= secondThreshold) //we know now we've passed firstThreshold test. { return(null); } } ; //check if we reached finalstate, if no return false. if (!(message.State is FinalState)) { return(null); } //else we have the final state. string bodyContents = ((FinalState)message.State).BodyContents; MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(bodyContents)); ConcatStream concatStream = null; Tuple <string, string> tuple; //concatenate the network stream to memorystream if (webRequest.Headers.TryGetValue("Content-Length".ToLower(), out tuple)) { //if the content-length header is present, make length queryable. //substract bodycontent's length from the queryable content length to get length of actual body. //since the 3rd parameter represents the second stream's "length" concatStream = new ConcatStream(ms, stream, int.Parse(tuple.Item2) - bodyContents.Length); } else { //else, call to Length property will throw an exception concatStream = new ConcatStream(ms, stream); } webRequest.Body = concatStream; //the body's first byte should be what the value actually is //NOTE: don't close client here, close them in responses. since we were successful. } catch (SocketException) { webRequest = null; //make sure it's null. } return(webRequest); }
public bool lengthQueryTest(ConcatStream c, bool shouldThrowException) { try { long length = c.Length; return(shouldThrowException == true); } catch { return(shouldThrowException == false); } }
private static WebRequest BuildRequest(TcpClient client) { NetworkStream clientStream = client.GetStream(); int ammountRead = 0; clientStream.ReadTimeout = (int)new TimeSpan(0, 0, 2).TotalMilliseconds; int startingSeconds = DateTime.Now.Second; int startingMinute = DateTime.Now.Minute; string fullRequest = ""; string destination = "/"; byte[] streamBuff = new byte[1024]; //create a buffer for reading int x = clientStream.Read(streamBuff, 0, 1024); int y = 0; int i = 0; //index of streamBuff ammountRead += x; string validReq = "GET / HTTP/1.1\r\n"; //I'm using this string to check against the request. while (x > 0 && y < validReq.Length) //while the ammount read is greater than 0 bytes { if (ammountRead > 2048) { clientStream.Close(); client.Close(); return(null); } if (DateTime.Now.Minute != startingMinute) //if it's a different minute, add 60 seconds when you check change in time { if (DateTime.Now.Second + 60 - startingSeconds > 10) //if 10 seconds has past since started reading. { clientStream.Close(); client.Close(); return(null); } } else if (DateTime.Now.Second - startingSeconds > 10) //if 10 seconds has past since started reading. { clientStream.Close(); client.Close(); return(null); } i = 0; fullRequest += Encoding.Default.GetString(streamBuff); while (i < x && y < validReq.Length) { if (y < 5 || y > 5) { //first part 'GET /' if (Convert.ToChar(streamBuff[i]) != validReq[y]) { //invalid request client.Close(); //close stream and return false return(null); } //else y++; //valid } else { //the request is giving the requested web page (this comes right after 'GET /') if (Convert.ToChar(streamBuff[i]) == ' ') { y++; } else //add this byte to the clientRequest { destination += Convert.ToChar(streamBuff[i]); } } i++; //increment i } if (y < validReq.Length) //only read if you need to. { x = clientStream.Read(streamBuff, 0, 1024); //read next bytes ammountRead += x; } else //otherwise, break the loop { break; } } //read in the headers while (true) { if (ammountRead > 102400) { clientStream.Close(); client.Close(); return(null); } if (fullRequest.Contains("\r\n\r\n")) { break; } else { //read more stuff x = clientStream.Read(streamBuff, 0, 1024); //read in more ammountRead += x; fullRequest += Encoding.Default.GetString(streamBuff); if (DateTime.Now.Minute != startingMinute) //if it's a different minute, add 60 seconds when you check change in time { if (DateTime.Now.Second + 60 - startingSeconds > 10) //if 10 seconds has past since started reading. { clientStream.Close(); client.Close(); return(null); } } else if (DateTime.Now.Second - startingSeconds > 10) //if 10 seconds has past since started reading. { clientStream.Close(); client.Close(); return(null); } } if (x <= 0) { return(null); //never had headers, nor a second \r\n. invalid request! } } string onlyHeaders; onlyHeaders = fullRequest.Substring(validReq.Length - 2); //before the \r\n string endHeaders = "\r\n\r\n"; int endHeadersCount = 0; while (endHeadersCount < onlyHeaders.Length) { if (onlyHeaders.Substring(endHeadersCount, 4) == endHeaders) { break; } endHeadersCount++; } List <Tuple <string, string> > headerList = new List <Tuple <string, string> >(); string headers = onlyHeaders.Substring(0, endHeadersCount); string[] splitters = new string[1]; splitters[0] = "\r\n"; string [] headerArray = headers.Split(splitters, StringSplitOptions.RemoveEmptyEntries); string[] headerSplitter; foreach (string headerCombo in headerArray) { headerCombo.Trim(); headerSplitter = headerCombo.Split(':'); if (headerSplitter.Length == 2) { headerList.Add(new Tuple <string, string>(headerSplitter[0], headerSplitter[1])); } } //populate from fullRequest string the URI, Method, version, etc future HW MemoryStream streamOne = new MemoryStream(); WebRequest request; int z = endHeadersCount + 4; //right after the last \r\n\r\n if (z < fullRequest.Length) { streamOne.Write(Encoding.ASCII.GetBytes(fullRequest), z, fullRequest.Length - z); ConcatStream jointStream = new ConcatStream(streamOne, client.GetStream()); request = new WebRequest(client, jointStream, headerList, "1.1", "GET", destination); //PLACE HOLDER LINE } else { request = new WebRequest(client, client.GetStream(), headerList, "1.1", "GET", destination); //PLACE HOLDER LINE } return(request); }
public void TestSecondConstructor() { Random rnd = new Random(); Stream defaultStream = new MemoryStream(); Stream one = new MemoryStream(); byte[] b2 = new byte[2000]; for (int i = 0; i < 1000; i++) { int number = rnd.Next(1000); defaultStream.Write(new byte[] { (byte)number }, 0, 1); one.Write(new byte[] { (byte)number }, 0, 1); } for (int i = 0; i < 2000; i++) { int number = rnd.Next(1000); defaultStream.Write(new byte[] { (byte)number }, 0, 1); b2 [i] = (byte)number; } Stream two = new NoSeekMemoryStream(b2); // Now defualtStream is what we expect our concat stream to be defaultStream.Seek(0, SeekOrigin.Begin); one.Seek(0, SeekOrigin.Begin); ConcatStream conStream = new ConcatStream(one, two, 300); Assert.AreEqual(300, conStream.Length); conStream = new ConcatStream(one, two, 3000); Assert.AreEqual(3000, conStream.Length); int bytesRead = 0; for (int i = 0; i <= defaultStream.Length;) { int randomRead = rnd.Next((int)defaultStream.Length); byte[] readBuf = new byte[randomRead]; byte[] expectetBuf = new byte[randomRead]; int amountRead = conStream.Read(readBuf, 0, randomRead); int expectedRead = defaultStream.Read(expectetBuf, 0, randomRead); Assert.AreEqual(expectetBuf, readBuf); Assert.AreEqual(expectedRead, amountRead); bytesRead += amountRead; i += randomRead; } Assert.Throws <NotImplementedException> (delegate { conStream.Position = conStream.Length + 5; }); Assert.AreEqual(0, conStream.Read(new byte[10], 0, 5)); Assert.Throws <ArgumentException> (delegate { conStream.Write(b2, 0, 300); }); }
public void TestWrite() { Stream one = new MemoryStream(); Stream two = new MemoryStream(); Random rnd = new Random(); one.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); two.Write(new byte[] { 6, 7, 8, 9, 10 }, 0, 5); one.Seek(0, SeekOrigin.Begin); two.Seek(0, SeekOrigin.Begin); Stream conStream = new ConcatStream(one, two); conStream.Seek(0, SeekOrigin.Begin); conStream.Seek(4, SeekOrigin.Begin); conStream.Seek(7, SeekOrigin.Begin); conStream.Seek(10, SeekOrigin.Begin); conStream.Seek(0, SeekOrigin.End); conStream.Seek(4, SeekOrigin.End); conStream.Seek(8, SeekOrigin.End); one = new MemoryStream(new byte[] { 5, 6, 7, 8 }); two = new MemoryStream(new byte[] { 5, 6, 7, 8 }); conStream = new ConcatStream(one, two); conStream.Write(new byte[5] { 1, 2, 3, 4, 5 }, 0, 5); byte[] buf = new byte[5]; conStream.Seek(0, SeekOrigin.Begin); conStream.Read(buf, 0, 5); Assert.AreEqual(new byte[5] { 1, 2, 3, 4, 5 }, buf); one = new MemoryStream(); two = new MemoryStream(); Stream defaultStream = new MemoryStream(); for (int i = 0; i < 920955; i++) { int number = rnd.Next(1000); one.Write(new byte[] { (byte)number }, 0, 1); } for (int i = 0; i < 2000; i++) { int number = rnd.Next(1000); two.Write(new byte[] { (byte)number }, 0, 1); } //byte[] writeBuf = new byte[10000000]; one.Seek(0, SeekOrigin.Begin); two.Seek(0, SeekOrigin.Begin); conStream = new ConcatStream(one, two); for (int i = 0; i < 10000000; i++) { int num = rnd.Next(); defaultStream.Write(new byte[] { (byte)num }, 0, 1); conStream.Write(new byte[] { (byte)num }, 0, 1); //writeBuf[i] = (byte)num; } //conStream.Write (writeBuf, 0, 10000000); //Assert.AreEqual (10000000, conStream.Length); conStream.Seek(0, SeekOrigin.Begin); defaultStream.Seek(0, SeekOrigin.Begin); for (int i = 0; i <= defaultStream.Length;) { int randomRead = rnd.Next((int)defaultStream.Length); byte[] readBuf = new byte[randomRead]; byte[] expectetBuf = new byte[randomRead]; int amountRead = conStream.Read(readBuf, 0, randomRead); int expectedRead = defaultStream.Read(expectetBuf, 0, randomRead); Assert.AreEqual(expectetBuf, readBuf); Assert.AreEqual(expectedRead, amountRead); i += randomRead; } conStream.Seek(0, SeekOrigin.Begin); conStream.Write(new byte[] { (byte)5 }, 0, 1); conStream.Seek(0, SeekOrigin.Begin); byte[] expectedBuf = new byte[1]; conStream.Read(expectedBuf, 0, 1); Assert.AreEqual(new byte[] { (byte)5 }, expectedBuf); // Using position setting instead of seeking conStream.Position = 0; conStream.Write(new byte[] { (byte)15 }, 0, 1); Assert.AreEqual(1, conStream.Position); conStream.Position = 0; expectedBuf = new byte[1]; conStream.Read(expectedBuf, 0, 1); Assert.AreEqual(new byte[] { (byte)15 }, expectedBuf); }
public void TestWrite() { Stream one = new MemoryStream(); Stream two = new MemoryStream(); Random rnd = new Random(); one.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); two.Write(new byte[] { 6, 7, 8, 9, 10 }, 0, 5); one.Seek(0, SeekOrigin.Begin); two.Seek(0, SeekOrigin.Begin); Stream conStream = new ConcatStream(one, two); conStream.Seek(0, SeekOrigin.Begin); conStream.Seek(4, SeekOrigin.Begin); conStream.Seek(7, SeekOrigin.Begin); conStream.Seek(10, SeekOrigin.Begin); conStream.Seek(0, SeekOrigin.End); conStream.Seek(4, SeekOrigin.End); conStream.Seek(8, SeekOrigin.End); one = new MemoryStream(new byte[] { 5, 6, 7, 8 }); two = new MemoryStream(new byte[] { 5, 6, 7, 8 }); conStream = new ConcatStream(one, two); conStream.Write(new byte[5] { 1, 2, 3, 4, 5 }, 0, 5); byte[] buf = new byte[5]; conStream.Seek(0, SeekOrigin.Begin); conStream.Read(buf, 0, 5); Assert.AreEqual(new byte[5] { 1, 2, 3, 4, 5 }, buf); one = new MemoryStream(); two = new MemoryStream(); Stream defaultStream = new MemoryStream(); for (int i = 0; i < 920955; i++) { int number = rnd.Next(1000); one.Write(new byte[] { (byte)number }, 0, 1); } for (int i = 0; i < 2000; i++) { int number = rnd.Next(1000); two.Write(new byte[] { (byte)number }, 0, 1); } //byte[] writeBuf = new byte[10000000]; one.Seek(0, SeekOrigin.Begin); two.Seek(0, SeekOrigin.Begin); conStream = new ConcatStream(one, two); for (int i = 0; i < 10000000; i++) { int num = rnd.Next(); defaultStream.Write(new byte[] { (byte)num }, 0, 1); conStream.Write(new byte[] { (byte)num }, 0, 1); //writeBuf[i] = (byte)num; } //conStream.Write (writeBuf, 0, 10000000); //Assert.AreEqual (10000000, conStream.Length); conStream.Seek(0, SeekOrigin.Begin); defaultStream.Seek(0, SeekOrigin.Begin); for (int i = 0; i <= defaultStream.Length;) { int randomRead = rnd.Next((int)defaultStream.Length); byte[] readBuf = new byte[randomRead]; byte[] expectetBuf = new byte[randomRead]; int amountRead = conStream.Read(readBuf, 0, randomRead); int expectedRead = defaultStream.Read(expectetBuf, 0, randomRead); Assert.AreEqual(expectetBuf, readBuf); Assert.AreEqual(expectedRead, amountRead); i += randomRead; } // Failed test that curreupt at posistion 0 // Seeking then writing to posistion0, seek there and read from position0. // I do not know why it is failing that test. This passes. conStream.Seek(0, SeekOrigin.Begin); conStream.Write(new byte[] { (byte)5 }, 0, 1); conStream.Seek(0, SeekOrigin.Begin); byte[] expectedBuf = new byte[1]; conStream.Read(expectedBuf, 0, 1); Assert.AreEqual(new byte[] { (byte)5 }, expectedBuf); }
private static WebRequest BuildRequest(TcpClient client) { Message message = new Message(); WebRequest webRequest = null; //make a 1mb buffer byte[] buffer = new byte[1024]; //translated to string form from data recieved from client socket. StringBuilder sb = new StringBuilder(); try { NetworkStream stream = client.GetStream(); //NOTE: Must dispose networkstream in webrequest responses. webRequest = new WebRequest(stream); //reference the stream so we can write response to it, then close. //read the networkstream's data into buffer //loop to recieve all data sent by the client. int bytesRead = 0; string dataRead = ""; string content = ""; do { bytesRead = stream.Read(buffer, 0, buffer.Length); dataRead = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead); content = message.CheckValidity(dataRead, webRequest); while (content != "") { content = message.CheckValidity(content, webRequest); if (message.State is ErrorState) { client.Close(); return(null); } } sb.Append(dataRead); //needs to exit once FinalState which tells us we finished } while(!(message.State is FinalState) && stream.DataAvailable); //check if we reached finalstate, if no return false. if (!(message.State is FinalState)) { return(null); } //else we have the final state. string bodyContents = ((FinalState)message.State).BodyContents; MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(bodyContents)); ConcatStream concatStream = null; Tuple <string, string> tuple; //concatenate the network stream to memorystream if (webRequest.Headers.TryGetValue("Content-Length".ToLower(), out tuple)) { //if the content-length header is present, make length queryable. //substract bodycontent's length from the queryable content length to get length of actual body. //since the 3rd parameter represents the second stream's "length" concatStream = new ConcatStream(ms, stream, int.Parse(tuple.Item2) - bodyContents.Length); } else { //else, call to Length property will throw an exception concatStream = new ConcatStream(ms, stream); } webRequest.Body = concatStream; //the body's first byte should be what the value actually is //NOTE: don't close client here, close them in responses. since we were successful. } catch (SocketException) { webRequest = null; //make sure it's null. } return(webRequest); }
public void SetLength_OnSetLengthAndWrite_DataIsCorrectlyWritten() { const int N_TEST_CASES = 1; const int MAX_STRING_LENGTH = int.MaxValue / 100; for (int i = 0; i < N_TEST_CASES; i++) { Console.WriteLine("SetLength_OnSetLengthAndWrite_DataIsCorrectlyWritten i = {0}", i); String randomString = RandomString(r.Next(0, MAX_STRING_LENGTH)); byte[] completeBuf = System.Text.Encoding.Unicode.GetBytes(randomString); // now create two streams int strALength = r.Next(0, randomString.Length); String strA = randomString.Substring(0, strALength); byte[] aBuf = System.Text.Encoding.Unicode.GetBytes(strA); String strB = randomString.Substring(strALength); byte[] bBuf = System.Text.Encoding.Unicode.GetBytes(strB); Stream A = new MemoryStream(aBuf); Stream B = new MemoryStream(); ConcatStream concat = new ConcatStream(A, B); concat.Seek(A.Length, SeekOrigin.Begin); int bytesToWrite = bBuf.Length; while (bytesToWrite > 0) { int nBytesToWrite = r.Next(0, bytesToWrite + 1); if (r.Next(1, int.MaxValue) % 2 == 0) { // change both streams position to messs wwith concatstream A.Position = r.Next(0, int.MaxValue); B.Position = r.Next(0, int.MaxValue); } else { A.Seek(r.Next(0, int.MaxValue), SeekOrigin.Begin); B.Seek(r.Next(0, int.MaxValue), SeekOrigin.Begin); } concat.Write(bBuf, bBuf.Length - bytesToWrite, nBytesToWrite); bytesToWrite -= nBytesToWrite; } concat.Seek(0, SeekOrigin.Begin); byte[] actual = new byte[concat.Length]; if (r.Next(1, int.MaxValue) % 2 == 0) { // change both streams position to messs wwith concatstream A.Position = r.Next(0, int.MaxValue); B.Position = r.Next(0, int.MaxValue); } else { A.Seek(r.Next(0, int.MaxValue), SeekOrigin.Current); B.Seek(r.Next(0, int.MaxValue), SeekOrigin.Current); } int nBytesRead = concat.Read(actual, 0, actual.Length); Assert.AreEqual(completeBuf.Length, nBytesRead); Assert.AreEqual(completeBuf, actual); } }