I have a program that repeatedly opens and closes TCP connections to a
host on the same computer:
while (true) {
using (TcpClient client = new TcpClient("localhost", 54321)) {
using (Stream stream = client.GetStream()) {
using(StreamReader reader = new StreamReader(stream)){
...
}
}
}
}
These connections have very short lifetimes, and it seems to me that I'm
somehow using them up! After a while, I get this SocketException:
"Only one usage of each socket address (protocol/network address/port)
is normally permitted."
However, if I catch this exception and sleep for a few seconds, I can
resume making connections again for a short while before another such
exception is thrown, and so on and so forth. Can somebody explain to me
what's going on? Please help, thanks in advance.
An aside: in the example code above, is it good practice to give the
StreamReader (or StreamWriter) its own "using" block? I'm thinking not,
because there always seems to be a way to directly access the underlying
stream and, hence, close the stream. Besides, that would make more
sense; it's the Stream, not the StreamReader, that's using resources,
right? And in that case, why is the StreamReader even made IDisposable
at all? To close its StreamReader(string filename) "shortcut"
constructor? I begin to think this shortcut was a bad idea....