I am having trouble sending streams of data from one socket to another
using the following code.
When the transmitter is running on the same machine as the receiver,
the data transmits perfectly. When the transmitter runs on another
machine, the data gets truncated at semi random places.
The data being transmitted is a unicode XML string. There is nothing
special about it other than being unicode.
The message stream is terminated with "</mos>\r\n". I read the stream
1 byte at a time in the code below. I have tried various other "block
read" methods with the same results.
This used to work when I was using .Net 2.0 under VS 2005. Since
upgrading to VS 2008, this no longer works correctly.
Is there anything I am doing wrong based on the code below or is there
something I have overlooked vis-a-vis VS 2008? Is there something
wrong with my network set up that would cause this - a service pack
release or something? I have tested this with the Windows Firewall on
and off - makes no difference.
Any help appreciated.
// The code that writes to the socket...
public void Write(NetworkStream OutputStream, string Msg)
{
Msg += "\r\n";
while (Msg.Contains("\r\n\r\n"))
Msg = Msg.Replace("\r\n\r\n", "\r\n");
byte[] OutputBuffer = Encoding.BigEndianUnicode.GetBytes(Msg);
OutputStream.Write(OutputBuffer, 0, OutputBuffer.GetLength(0));
OutputStream.Flush();
}
// The code that reads the socket...
public string Read(NetworkStream InputStream, string EOM)
{
StreamReader Reader = new StreamReader(InputStream,
Encoding.BigEndianUnicode);
StringBuilder MsgText = new StringBuilder();
Int32 InChar = -1;
while (true)
{
// If the next character == -1, we have been cut off and
disconnected or there was an error
// in the message being sent to the reader. Either way, stop
reading.
if ((InChar = Reader.Peek()) == -1)
{
if (!MsgText.ToString().EndsWith(EOM))
{
string ErrorMessage = string.Format("Error: Incomplete
Message\r\n\r\n{0}\r\n[PREMATURE END OF MESSAGE]",
MsgText.ToString());
MOSNetTraceSource.TraceData(TraceEventType.Error,
ErrorMessage);
LogWriter.WriteError(ErrorMessage);
}
return (null);
}
InChar = Reader.Read();
MsgText.Append((char)InChar);
if (MsgText.Length 10 && (char)InChar == '\n')
{
if (MsgText.ToString().EndsWith(EOM))
{
break;
}
}
return(MsgText.ToString());
}