473,657 Members | 2,801 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why does StreamReader get stuck

using System;
using System.Collecti ons;
using System.IO;
using System.Net;
using System.Net.Sock ets;
using System.Threadin g;

class HttpProcessor
{
private Socket s;
private BufferedStream bs;
private StreamReader sr;
private StreamWriter sw;
private String method;
private String url;
private String protocol;
private Hashtable hashTable;

public HttpProcessor(S ocket s)
{
this.s = s;
hashTable = new Hashtable();
}

public void process()
{
NetworkStream ns = new NetworkStream(s , FileAccess.Read Write, false);
bs = new BufferedStream( ns);
sr = new StreamReader(bs );
sw = new StreamWriter(bs );

sr.Peek (); <--------------- stuck, or sr.Read (...) stuck too

parseRequest();
readHeaders();
writeURL();

s.Shutdown (SocketShutdown .Both);
s.Close ();
}

public void parseRequest()
{
String request = sr.ReadLine();
string[] tokens = request.Split(n ew char[]{' '});
method = tokens[0];
url = tokens[1];
protocol = tokens[2];
}

public void readHeaders()
{
String line;
while((line = sr.ReadLine()) != null && line != "")
{
string[] tokens = line.Split(new char[]{':'});
String name = tokens[0];
String value = "";
for(int i = 1; i < tokens.Length; i++)
{
value += tokens[i];
if(i < tokens.Length - 1) tokens[i] += ":";
}
hashTable[name] = value;
}
}

public void writeURL()
{
try
{
FileStream fs = new FileStream(url. Length <= 1 ? "index.html " :
url.Substring(1 ), FileMode.Open, FileAccess.Read );
writeSuccess();
BufferedStream bs2 = new BufferedStream( fs);
byte[] bytes = new byte[4096];
int read;
while((read = bs2.Read(bytes, 0, bytes.Length)) != 0)
{
bs.Write(bytes, 0, read);
}
bs.Flush ();
bs2.Close();
}
catch(FileNotFo undException)
{
writeFailure();
sw.WriteLine("F ile not found: " + url);
}
}

public void writeSuccess()
{
sw.WriteLine("H TTP/1.0 200 OK");
sw.WriteLine("C onnection: close");
sw.WriteLine();
sw.Flush();
}

public void writeFailure()
{
sw.WriteLine("H TTP/1.0 404 File not found");
sw.WriteLine("C onnection: close");
sw.WriteLine();
}
}

public class HttpServer
{

// =============== =============== =============== ===============
// Data

protected int port;

// =============== =============== =============== ===============
// Constructor

public HttpServer() : this(80)
{
}

public HttpServer(int port)
{
this.port = port;
}

// =============== =============== =============== ===============
// Listener

public void listen()
{
Socket listener = new Socket(0, SocketType.Stre am, ProtocolType.Tc p);
listener.Bind (new IPEndPoint(IPAd dress.Any, port));
listener.Blocki ng = true;
listener.Listen ((int) SocketOptionNam e.MaxConnection s);
while(true)
{
Socket s = listener.Accept ();
HttpProcessor processor = new HttpProcessor(s );
Thread thread = new Thread(new ThreadStart(pro cessor.process) );
thread.Start();
}
}

// =============== =============== =============== ===============
// Main

public static int Main(String[] args)
{
HttpServer httpServer;
if(args.GetLeng th(0) > 0)
httpServer = new HttpServer (Int32.Parse (args[0]));
else
httpServer = new HttpServer();
Thread thread = new Thread(new ThreadStart(htt pServer.listen) );
thread.Start();
return 0;
}
}

-----------
NetworkStream ns = new NetworkStream(s , FileAccess.Read Write, false);
bs = new BufferedStream( ns);
sr = new StreamReader(bs );
sw = new StreamWriter(bs );

sr.Read (...) call gets blocked?! so does sr.Peek () ?!!!!!!
sw.Write (...) is okay

----

NetworkStream ns = new NetworkStream(s , FileAccess.Read Write, false);
bs = new BufferedStream( ns);
sr = new StreamReader(ns ); <---- notice: ns not bs
sw = new StreamWriter(bs );

sr.Peek and Read now okay

----
So NetworkStream + BufferedStream + StreamReader = hang? WHY? HELP!
Nov 16 '05 #1
4 8736
Astronomically Confused,

Most likely, it gets stuck because you are using a buffered stream
instance. You shouldn't use this for network streams, because you will
never get an end of stream indicator. Rather it is trying to read a block
from the stream, and since whatever you are connected to isn't going to send
anymore, it hangs.

Remove the BufferedStream, and you should be fine.

A buffered stream won't work here because you need markers in your
messages that require you to read byte by byte (or character by character)
to identify those markers. Some message formats prepend the length to the
message, or have the length of the message embedded in the message
somewhere. This allows you to read larger chunks later on. However, this
does not seem to be the case here.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Astronomic ally Confused" <Astronomical ly
Co******@discus sions.microsoft .com> wrote in message
news:A2******** *************** ***********@mic rosoft.com...
using System;
using System.Collecti ons;
using System.IO;
using System.Net;
using System.Net.Sock ets;
using System.Threadin g;

class HttpProcessor
{
private Socket s;
private BufferedStream bs;
private StreamReader sr;
private StreamWriter sw;
private String method;
private String url;
private String protocol;
private Hashtable hashTable;

public HttpProcessor(S ocket s)
{
this.s = s;
hashTable = new Hashtable();
}

public void process()
{
NetworkStream ns = new NetworkStream(s , FileAccess.Read Write,
false);
bs = new BufferedStream( ns);
sr = new StreamReader(bs );
sw = new StreamWriter(bs );

sr.Peek (); <--------------- stuck, or sr.Read (...) stuck too

parseRequest();
readHeaders();
writeURL();

s.Shutdown (SocketShutdown .Both);
s.Close ();
}

public void parseRequest()
{
String request = sr.ReadLine();
string[] tokens = request.Split(n ew char[]{' '});
method = tokens[0];
url = tokens[1];
protocol = tokens[2];
}

public void readHeaders()
{
String line;
while((line = sr.ReadLine()) != null && line != "")
{
string[] tokens = line.Split(new char[]{':'});
String name = tokens[0];
String value = "";
for(int i = 1; i < tokens.Length; i++)
{
value += tokens[i];
if(i < tokens.Length - 1) tokens[i] += ":";
}
hashTable[name] = value;
}
}

public void writeURL()
{
try
{
FileStream fs = new FileStream(url. Length <= 1 ? "index.html " :
url.Substring(1 ), FileMode.Open, FileAccess.Read );
writeSuccess();
BufferedStream bs2 = new BufferedStream( fs);
byte[] bytes = new byte[4096];
int read;
while((read = bs2.Read(bytes, 0, bytes.Length)) != 0)
{
bs.Write(bytes, 0, read);
}
bs.Flush ();
bs2.Close();
}
catch(FileNotFo undException)
{
writeFailure();
sw.WriteLine("F ile not found: " + url);
}
}

public void writeSuccess()
{
sw.WriteLine("H TTP/1.0 200 OK");
sw.WriteLine("C onnection: close");
sw.WriteLine();
sw.Flush();
}

public void writeFailure()
{
sw.WriteLine("H TTP/1.0 404 File not found");
sw.WriteLine("C onnection: close");
sw.WriteLine();
}
}

public class HttpServer
{

// =============== =============== =============== ===============
// Data

protected int port;

// =============== =============== =============== ===============
// Constructor

public HttpServer() : this(80)
{
}

public HttpServer(int port)
{
this.port = port;
}

// =============== =============== =============== ===============
// Listener

public void listen()
{
Socket listener = new Socket(0, SocketType.Stre am,
ProtocolType.Tc p);
listener.Bind (new IPEndPoint(IPAd dress.Any, port));
listener.Blocki ng = true;
listener.Listen ((int) SocketOptionNam e.MaxConnection s);
while(true)
{
Socket s = listener.Accept ();
HttpProcessor processor = new HttpProcessor(s );
Thread thread = new Thread(new ThreadStart(pro cessor.process) );
thread.Start();
}
}

// =============== =============== =============== ===============
// Main

public static int Main(String[] args)
{
HttpServer httpServer;
if(args.GetLeng th(0) > 0)
httpServer = new HttpServer (Int32.Parse (args[0]));
else
httpServer = new HttpServer();
Thread thread = new Thread(new ThreadStart(htt pServer.listen) );
thread.Start();
return 0;
}
}

-----------
NetworkStream ns = new NetworkStream(s , FileAccess.Read Write, false);
bs = new BufferedStream( ns);
sr = new StreamReader(bs );
sw = new StreamWriter(bs );

sr.Read (...) call gets blocked?! so does sr.Peek () ?!!!!!!
sw.Write (...) is okay

----

NetworkStream ns = new NetworkStream(s , FileAccess.Read Write, false);
bs = new BufferedStream( ns);
sr = new StreamReader(ns ); <---- notice: ns not bs
sw = new StreamWriter(bs );

sr.Peek and Read now okay

----
So NetworkStream + BufferedStream + StreamReader = hang? WHY? HELP!

Nov 16 '05 #2
In your reply you suggested that we should not use BufferedStream with
NetworkStream because an end of buffer marker will not show up. This claim is
false because in my experiment, I am able to direct read a block of bytes
from the BufferedStream just fine.

It is when using a StreamReader linked to a BufferedStream does the blocking
problem occur. StreamReader's peek or read causes the system to infinitely
wait for incoming data. Perhaps StreamReader's implementation does expect an
end of buffer marker; should your explanation be applied here, then it would
be correct.

The source code to the StreamReader's implementation is not open-source so
the problem must be further isolated through experimentation .

I can tell you that for a client-side C# application the StreamReader on the
BufferedStream in fact works. In the server-side implimentation, the
StreamReader blocks forever on peeks or reads. Thus, my experiments point
that the problem has something to do with sockets created through the Listen
method.

My intuition leads me to think that this is a bug. It exists in both .NET
1.1 and 2.0 beta run-times. Please verify this problem when you get the
chance. I appreciate it.
Nov 16 '05 #3
Astronomically Confused,
just for your information, there are ways to have a look at the
StreamReader's implementation, try using Lutz Roeder's Reflector or have a
look at Rotor sources.
In my opinion, this is not a bug in the framework.

"Astronomic ally Confused" <Astronomical ly
Co******@discus sions.microsoft .com> wrote in message
news:55******** *************** ***********@mic rosoft.com...
In your reply you suggested that we should not use BufferedStream with
NetworkStream because an end of buffer marker will not show up. This claim is false because in my experiment, I am able to direct read a block of bytes
from the BufferedStream just fine.

It is when using a StreamReader linked to a BufferedStream does the blocking problem occur. StreamReader's peek or read causes the system to infinitely
wait for incoming data. Perhaps StreamReader's implementation does expect an end of buffer marker; should your explanation be applied here, then it would be correct.

The source code to the StreamReader's implementation is not open-source so
the problem must be further isolated through experimentation .

I can tell you that for a client-side C# application the StreamReader on the BufferedStream in fact works. In the server-side implimentation, the
StreamReader blocks forever on peeks or reads. Thus, my experiments point
that the problem has something to do with sockets created through the Listen method.

My intuition leads me to think that this is a bug. It exists in both .NET
1.1 and 2.0 beta run-times. Please verify this problem when you get the
chance. I appreciate it.

Nov 17 '05 #4
Did you ever get this figured out? I'm having similiar issues.

--
Thanks
Joe
"Astronomic ally Confused" wrote:
using System;
using System.Collecti ons;
using System.IO;
using System.Net;
using System.Net.Sock ets;
using System.Threadin g;

class HttpProcessor
{
private Socket s;
private BufferedStream bs;
private StreamReader sr;
private StreamWriter sw;
private String method;
private String url;
private String protocol;
private Hashtable hashTable;

public HttpProcessor(S ocket s)
{
this.s = s;
hashTable = new Hashtable();
}

public void process()
{
NetworkStream ns = new NetworkStream(s , FileAccess.Read Write, false);
bs = new BufferedStream( ns);
sr = new StreamReader(bs );
sw = new StreamWriter(bs );

sr.Peek (); <--------------- stuck, or sr.Read (...) stuck too

parseRequest();
readHeaders();
writeURL();

s.Shutdown (SocketShutdown .Both);
s.Close ();
}

public void parseRequest()
{
String request = sr.ReadLine();
string[] tokens = request.Split(n ew char[]{' '});
method = tokens[0];
url = tokens[1];
protocol = tokens[2];
}

public void readHeaders()
{
String line;
while((line = sr.ReadLine()) != null && line != "")
{
string[] tokens = line.Split(new char[]{':'});
String name = tokens[0];
String value = "";
for(int i = 1; i < tokens.Length; i++)
{
value += tokens[i];
if(i < tokens.Length - 1) tokens[i] += ":";
}
hashTable[name] = value;
}
}

public void writeURL()
{
try
{
FileStream fs = new FileStream(url. Length <= 1 ? "index.html " :
url.Substring(1 ), FileMode.Open, FileAccess.Read );
writeSuccess();
BufferedStream bs2 = new BufferedStream( fs);
byte[] bytes = new byte[4096];
int read;
while((read = bs2.Read(bytes, 0, bytes.Length)) != 0)
{
bs.Write(bytes, 0, read);
}
bs.Flush ();
bs2.Close();
}
catch(FileNotFo undException)
{
writeFailure();
sw.WriteLine("F ile not found: " + url);
}
}

public void writeSuccess()
{
sw.WriteLine("H TTP/1.0 200 OK");
sw.WriteLine("C onnection: close");
sw.WriteLine();
sw.Flush();
}

public void writeFailure()
{
sw.WriteLine("H TTP/1.0 404 File not found");
sw.WriteLine("C onnection: close");
sw.WriteLine();
}
}

public class HttpServer
{

// =============== =============== =============== ===============
// Data

protected int port;

// =============== =============== =============== ===============
// Constructor

public HttpServer() : this(80)
{
}

public HttpServer(int port)
{
this.port = port;
}

// =============== =============== =============== ===============
// Listener

public void listen()
{
Socket listener = new Socket(0, SocketType.Stre am, ProtocolType.Tc p);
listener.Bind (new IPEndPoint(IPAd dress.Any, port));
listener.Blocki ng = true;
listener.Listen ((int) SocketOptionNam e.MaxConnection s);
while(true)
{
Socket s = listener.Accept ();
HttpProcessor processor = new HttpProcessor(s );
Thread thread = new Thread(new ThreadStart(pro cessor.process) );
thread.Start();
}
}

// =============== =============== =============== ===============
// Main

public static int Main(String[] args)
{
HttpServer httpServer;
if(args.GetLeng th(0) > 0)
httpServer = new HttpServer (Int32.Parse (args[0]));
else
httpServer = new HttpServer();
Thread thread = new Thread(new ThreadStart(htt pServer.listen) );
thread.Start();
return 0;
}
}

-----------
NetworkStream ns = new NetworkStream(s , FileAccess.Read Write, false);
bs = new BufferedStream( ns);
sr = new StreamReader(bs );
sw = new StreamWriter(bs );

sr.Read (...) call gets blocked?! so does sr.Peek () ?!!!!!!
sw.Write (...) is okay

----

NetworkStream ns = new NetworkStream(s , FileAccess.Read Write, false);
bs = new BufferedStream( ns);
sr = new StreamReader(ns ); <---- notice: ns not bs
sw = new StreamWriter(bs );

sr.Peek and Read now okay

----
So NetworkStream + BufferedStream + StreamReader = hang? WHY? HELP!

Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
7992
by: Daniel P. | last post by:
I'm using StreamReader to read a text file and sometimes I get an error saying that the file is opened by someone else. I haven't found any info about how to set a flag to tell StreamReader to open the file in shared mode and read mode. Thanks! Daniel
4
5526
by: Mike | last post by:
I created a StreamReader object from a local file on my c:\ drive StreamReader srTemp = new StreamReader("C:\\myFile.txt") I then used a RegEx to strip out all the html and save what's left to a string object So far so good. So now I'm left with just the text Question 1.When I created a second streamreader object and pass in the name of this string I got this erro
9
12748
by: oafyuf | last post by:
Hi, I'm having performanbce issues with StreamReader and was wondering what I could do to improve it... The following takes around 3 seconds to process! The content of the response is: "<?xml version="1.0" ?><ERROR>ORA-01403: no data found</ERROR>" HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strURIQuery);
2
2732
by: rVo | last post by:
In a VB.Net application I create a new streamreader and use it's ReadToEnd function to read the contents of a htmlfile. Inside the file there are some signs like öéèêë..., these signs are not present in the stream that has been read by the ReadToEnd function though. This problem occured in a program that has been running succesfully for about a yeatr already. Could this have been caused by recent patches or an upgrade of the dot net...
3
1459
by: Raghu | last post by:
I have following schema: <?xml version="1.0" encoding="utf-8"?> <xs:schema elementFormDefault="qualified" targetNamespace="http://mycompany.services.customer2/types/restricted" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://mycompany.services.customer2/types/restricted"> <xs:simpleType name="FirstName">
4
2231
by: Mike R | last post by:
Hi All, I'm trying to read a file that has the following format, its a variable record file, the first byte determines how to process the rest. byte 1 = either 0,1,2,3 4 bytes = size of the file other bytes = lots of stuff I'm bascially stuck on getting the 4 bytes into an int32!
1
2762
by: Sladan | last post by:
Im trying to read a xml-file with a StreamReader. For the moment I'm using the following code. streamReader = new StreamReader(stream, System.Text.Encoding.Default); string feedData = streamReader.ReadToEnd(); I'm using System.Text.Encoding.Default so that I can get some swedish characters working. But I'm having problem when reading a xml-file that's encoded with UTF-8. In the beginning of the xml-files you have the encoding for the...
0
2883
by: vishnu | last post by:
Hi, Am trying to post the data over https and am getting error in httpwebresponse.getResponseStream.Please help me to get rid of this issue. Here is the message from immediate window ?myResp.GetResponseStream() {System.Net.ConnectStream}
0
2348
by: rajana | last post by:
Dear All, We have Ansi file with german characters (Ä / Ø) , We are using Streamreader to read the contents of the file. But Readline() not able to read the German characters. We tried all possibilities of calling the streamreader, but nothing worked. Dim sr As StreamReader = New StreamReader(Filename, System.Text.Encoding.Default, True) Dim sr As StreamReader = New StreamReader(Filename, _System.Text.Encoding.ASCII, False, 512)
0
8403
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8316
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8833
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8737
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8509
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5636
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4327
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2735
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1730
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.