Getting answer from Jabber Server

2019-08-27 21:47发布

问题:

I want connect with my jabber server and read server answer:

       DnsEndPoint host = new DnsEndPoint("talk.google.com", 5222);
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        SocketAsyncEventArgs args = new SocketAsyncEventArgs();

public void start()
{
 string message = "<?xml version=1.0?><stream:streamto='gmail.com'xmlns='jabber:client'xmlns:stream='http://etherx.jabber.org/streams'version='1.0'>";

            var buffer = Encoding.UTF8.GetBytes(message);

            args.RemoteEndPoint = host;
            args.Completed += SocketAsyncEventArgs_Completed;
            args.SetBuffer(buffer, 0, buffer.Length);

            bool completesAsynchronously = socket.ConnectAsync(args);

            if (!completesAsynchronously)
            {
                SocketAsyncEventArgs_Completed(args.ConnectSocket, args);
            }
}

 private void SocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError != SocketError.Success)
            {
                 Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show("Error during socket operation: " + e.SocketError));
                return;
            }
            byte[] buffer = e.Buffer;
            XDocument temp = ConvertByteArrayToXml(buffer);

        }

XDocument ConvertByteArrayToXml(byte[] data)
        {
            XmlReaderSettings settings = new XmlReaderSettings();

            using (MemoryStream stream = new MemoryStream(data))
            using (XmlReader reader = XmlReader.Create(stream, settings))
            {
                return XDocument.Load(reader);
            }
        }

At Return XDocument.Load(reader) I get exeption '1.0' is an unexpected token. The expected token is '"' or '''. How can solve it?

Why I want it? Because when I authorize myself and change status it not affect it at my account.

回答1:

This (in your declaration for message):

<?xml version=1.0?>

is an invalid XML declaration. As per the exception, you want:

<?xml version="1.0" ?>

Note that this has nothing to do with Jabber or sockets, and everything to do with XML. It's important to pay attention to exception messages and stack traces, so you can diagnose this sort of thing for yourself: you need to be able to isolate the area of the problem, so you can tackle just that one bit in isolation.

(The rest of that XML looks pretty bust, too, by the way.)



回答2:

Please do not write your own XMPP library from scratch, but choose one of the existing ones.

You're not going to be successful thinking of the XML you receive like a file, which is where your Unexpected end of file has occurred error is coming from. You must parse the XML incrementally.