Reading and writing XML over an SslStream
- by Mark
I want to read and write XML data over an SslStream.
The data (written and read) consists of objects serialized by an
XmlSerializer.
I have tried the following; (left some details out for clarity!)
TcpClient tcpClient = new TcpClient(server, port);
SslStream sslStream = new SslStream(tcpClient.GetStream(), true,
new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient(server);
XmlReader xmlReader = XmlReader.Create(sslStream,readerSettings);
XmlWriter xmlWriter = XmlWriter.Create(sslStream,writerSettings);
myClass c = new myClass ();
XmlSerializer serializer = new XmlSerializer(typeof(myClass));
serializer.Serialize(xmlWriter, c);
myClass c2 = (myClass )serializer.Deserialize(xmlReader);
First of all, it appears that writing to the stream succeeds. But the
XmlSerializer throws an error because of invalid XML. It appears that the
first character read from the stream is '00' or a null-character. (I have
googled this problem, and see a million people with the same 'problem', but
no viable solution.)
I can work around this 'issue' by using a StreamReader, read everything into
a string and then use that string as input for another stream that the
serializer can use. (Very dirty, but it works.)
Second problem is, that when I try to use the same SslStream to write a
second request, I do not get a response from the Reader. (The server DOES
send a valid XML response though!) So the serializer.Serialize(xmlWriter,
c3) works, but reading from the stream yields no results. I have tried
several different classes that implement Stream. (StreamReader,
XmlTextReader, etc.)
Anyone has an idea how reading and writing XML data to and from an SslStream
is supposed to work?
Thanks in advance!