Yes, each listener listen to a different port.
I am using 8 ports for now.
Any particular reason why? One port should be sufficient, assuming the
rest of your code is designed correctly.
For sure, you've got at least one serious bug:
[...]
i = stream.Read(bytes, 0, bytes.Length);
while (i > 0)
{
i = stream.Read(bytes, 0, bytes.Length);
Whatever bytes you read from the stream in your first call to Read(), you
simply discard. I'm surprised that you get _any_ successful results with
this code. Maybe you have some bug elsewhere that somehow offsets this
bug.
And here's a line of code that could be bug if it was extrapolated to
other encodings:
// Translate data bytes to a ASCII string.
data += System.Text.Encoding.ASCII.GetString(bytes, 0, i);
I'd have to spend a little more time reviewing the Encoding class stuff,
but my recollection is that you need to get a single Encoding instance and
use it repeatedly when decoding strings from a byte stream. Otherwise, if
you receive partial data, it will get lost between calls to GetString().
Since ASCII is always only one byte per character, this isn't a problem
with ASCII per se. But if you were to change your design to transmit
encodings it would be.
But for now, the main thing you need to fix is to stop discarding the
first sequence of bytes you receive. As a minimal change to your code,
I'd suggest something like this:
i = stream.Read(bytes, 0, bytes.Length);
while (i > 0 && !data.EndsWith("\r"))
{
// Translate data bytes to a ASCII string.
data += System.Text.Encoding.ASCII.GetString(bytes, 0, i);
i = stream.Read(bytes, 0, bytes.Length);
}
You may also want to consider changing your code so that it uses a
StringBuilder to accumulate the string, rather than repeatedly
accumulating the string being read in. Whether it's really a problem
depends on how many times you're actually doing to concatenate and how
long the string will eventually get. But for large strings, StringBuilder
will be much more efficient.
Pete