473,387 Members | 1,517 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

why does StreamReader get stuck

using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

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(Socket s)
{
this.s = s;
hashTable = new Hashtable();
}

public void process()
{
NetworkStream ns = new NetworkStream(s, FileAccess.ReadWrite, 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(new 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(FileNotFoundException)
{
writeFailure();
sw.WriteLine("File not found: " + url);
}
}

public void writeSuccess()
{
sw.WriteLine("HTTP/1.0 200 OK");
sw.WriteLine("Connection: close");
sw.WriteLine();
sw.Flush();
}

public void writeFailure()
{
sw.WriteLine("HTTP/1.0 404 File not found");
sw.WriteLine("Connection: 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.Stream, ProtocolType.Tcp);
listener.Bind (new IPEndPoint(IPAddress.Any, port));
listener.Blocking = true;
listener.Listen((int) SocketOptionName.MaxConnections);
while(true)
{
Socket s = listener.Accept();
HttpProcessor processor = new HttpProcessor(s);
Thread thread = new Thread(new ThreadStart(processor.process));
thread.Start();
}
}

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

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

-----------
NetworkStream ns = new NetworkStream(s, FileAccess.ReadWrite, 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.ReadWrite, 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 8689
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.com

"Astronomically Confused" <Astronomically
Co******@discussions.microsoft.com> wrote in message
news:A2**********************************@microsof t.com...
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

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(Socket s)
{
this.s = s;
hashTable = new Hashtable();
}

public void process()
{
NetworkStream ns = new NetworkStream(s, FileAccess.ReadWrite,
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(new 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(FileNotFoundException)
{
writeFailure();
sw.WriteLine("File not found: " + url);
}
}

public void writeSuccess()
{
sw.WriteLine("HTTP/1.0 200 OK");
sw.WriteLine("Connection: close");
sw.WriteLine();
sw.Flush();
}

public void writeFailure()
{
sw.WriteLine("HTTP/1.0 404 File not found");
sw.WriteLine("Connection: 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.Stream,
ProtocolType.Tcp);
listener.Bind (new IPEndPoint(IPAddress.Any, port));
listener.Blocking = true;
listener.Listen((int) SocketOptionName.MaxConnections);
while(true)
{
Socket s = listener.Accept();
HttpProcessor processor = new HttpProcessor(s);
Thread thread = new Thread(new ThreadStart(processor.process));
thread.Start();
}
}

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

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

-----------
NetworkStream ns = new NetworkStream(s, FileAccess.ReadWrite, 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.ReadWrite, 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.

"Astronomically Confused" <Astronomically
Co******@discussions.microsoft.com> wrote in message
news:55**********************************@microsof t.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
"Astronomically Confused" wrote:
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

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(Socket s)
{
this.s = s;
hashTable = new Hashtable();
}

public void process()
{
NetworkStream ns = new NetworkStream(s, FileAccess.ReadWrite, 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(new 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(FileNotFoundException)
{
writeFailure();
sw.WriteLine("File not found: " + url);
}
}

public void writeSuccess()
{
sw.WriteLine("HTTP/1.0 200 OK");
sw.WriteLine("Connection: close");
sw.WriteLine();
sw.Flush();
}

public void writeFailure()
{
sw.WriteLine("HTTP/1.0 404 File not found");
sw.WriteLine("Connection: 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.Stream, ProtocolType.Tcp);
listener.Bind (new IPEndPoint(IPAddress.Any, port));
listener.Blocking = true;
listener.Listen((int) SocketOptionName.MaxConnections);
while(true)
{
Socket s = listener.Accept();
HttpProcessor processor = new HttpProcessor(s);
Thread thread = new Thread(new ThreadStart(processor.process));
thread.Start();
}
}

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

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

-----------
NetworkStream ns = new NetworkStream(s, FileAccess.ReadWrite, 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.ReadWrite, 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
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...
4
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...
9
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: ...
2
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...
3
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"...
4
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...
1
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 =...
0
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 ...
0
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...

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.