[ACCEPTED]-C# - StreamReader.ReadLine does not work properly!-bufferedstream
A typical line-reader is something like:
using(StreamReader reader = new StreamReader(Socket.GetStream(), Encoding.UTF8)) {
string line;
while((line = reader.ReadLine()) != null) {
// do something with line
}
}
(note 14 the using
to ensure we Dispose()
it even if we get an 13 error, and the loop)
If you want, you could 12 abstract this (separation of concerns) with 11 an iterator block:
static IEnumerable<string> ReadLines(Stream source, Encoding encoding) {
using(StreamReader reader = new StreamReader(source, encoding)) {
string line;
while((line = reader.ReadLine()) != null) {
yield return line;
}
}
}
(note we've moved this 10 into a function and removed the "do something", replacing 9 it with "yield return", which creates an 8 iterator (a lazily iterated, non-buffering 7 state machine)
We would then consume this 6 as simply as:
foreach(string line in ReadLines(Socket.GetStream(), Encoding.UTF8)) {
// do something with line
}
Now our processing code doesn't 5 need to worry about how to read lines - simply 4 given a sequence of lines, do something with 3 them.
Note that the using
(Dispose()
) applies to TcpClient
too; you 2 should make a habit of checking for IDisposable
; for 1 example (still including your error-logging):
using(TcpClient tcpClient = new TcpClient()) {
try {
tcpClient.Connect("localhost", serverPort);
StreamWriter writer = new StreamWriter(tcpClient.GetStream(), Encoding.UTF8);
writer.AutoFlush = true;
writer.WriteLine("login>user,pass");
writer.WriteLine("print>param1,param2,param3");
} catch (Exception ex) {
Console.Error.WriteLine(ex.ToString());
}
}
The while in your server code is setup to 8 only read one line per connection. You'll 7 need another while within the try to read 6 all of the lines being sent. I think once 5 that stream is setup on the client side, it 4 is going to send all of the data. Then 3 on the server side, your stream is effectively 2 only reading one line from that particular 1 stream.
public string READS()
{
byte[] buf = new byte[CLI.Available];//set buffer
CLI.Receive(buf);//read bytes from stream
string line = UTF8Encoding.UTF8.GetString(buf);//get string from bytes
return line;//return string from bytes
}
public void WRITES(string text)
{
byte[] buf = UTF8Encoding.UTF8.GetBytes(text);//get bytes of text
CLI.Send(buf);//send bytes
}
CLI is a socket. for some rezone the TcpClient 3 class doesn't work right on my pc any more, but 2 the Socket class works just fine.
UTF-8 is 1 the stranded StreamReader / Writer Encoding
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.