Katharina
Katharina

Reputation: 39

Sending stream via socket

Sorry for this type of question but I am writing a test soon on this and have no clue on the following possible question: A web server uses the following c#-code fragment to write a static web-object into the socket-object 'sock'. For which type of web-objects does the code work and which it doesn't? With what .Net-class could the code be improved?

...
f = new FileStream(pathName, FileMode.Open, FileAccess.Read);
StreamReader sReader = new StreamReader(f);
sReader.BaseStream.Seek(0, SeekOrigin.Begin);
String s = sReader.ReadlLine();
while (s != null)
{
  sock.Send(System.Text.Encoding.ASCII.GetBytes(s));
  s = sReader.ReadLine();
}
sReader.Close();
...

Upvotes: 1

Views: 79

Answers (1)

usr
usr

Reputation: 171178

What's a "web-object"? I think your teacher made that term up. I assume this means "file".

Anyway, this will fail if the content is not exactly representable as ASCII.

There is no need to go through text at all. Just copy over the bytes:

f.CopyTo(new NetworkStream(sock));

Any other way to copy the bytes unmodified is also fine.

Be aware that you need to wrap resources such as all those streams and sockets into using in order to not leak.

Upvotes: 2

Related Questions