如何使用XMPP协议正确连接strophe.js客户端和Prosody服务器

时间:2014-12-09 22:10:03

标签: xmpp strophe prosody-im

我已经安装并配置了Prosody服务器。它侦听标准localhost:5222。在配置文件中添加了admin - user1@example.com。对服务器的每个请求都以错误结束:

<stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" id="" version="1.0">
    <stream:error>
        <not-well-formed xmlns="urn:ietf:params:xml:ns:xmpp-streams"/>
    </stream:error>
</stream:stream>

作为客户,我想使用strophe.js。我只发送存在节($ pres)。这是我的代码。

'use strict';

angular.module('xmppTestApp')
    .controller('ChatCtrl', function () {

    var vm = this;

    var url = "http://localhost:5222";
    var connection = null; 

    var output = document.getElementById("output");

    function log(message) {
        var line = document.createElement("div");
        line.textContent = message;
        output.appendChild(line);
    }

    function connectHandler(cond) {
        if (cond == Strophe.Status.CONNECTED) {
            log("connected");
            connection.send($pres());
        }
        else {
            log("not connected");
        }
    }

    vm.connectB = function() {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;

        console.info(url);
        console.info(username);
        console.info(password);

        connection = new Strophe.Connection(url);
        connection.connect(username, password, connectHandler);
    }
});

在控制台中我看到错误:

XMLHttpRequest cannot load http://localhost:5222/. No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:9000' is therefore not allowed access.

如何添加Access-Control-Allow-Origin&#39;标题是我的请求?

当我尝试向localhost发送请求时:5222(没有http)我得到了:

XMLHttpRequest cannot load localhost:5222. Cross origin requests are only supported for HTTP.

当我通过websocket发送它时,我得到了:

WebSocket connection to 'ws://localhost:5222/' failed: Error during WebSocket handshake: Unexpected response code: 200 

Fiddler为我提供了协议违规报告:

The server didn't return properly-formatted HTTP Headers. Maybe missing altogether 
(e.g. HTTP/0.9), maybe only \r\r instead of \r\n\r\n?

1 个答案:

答案 0 :(得分:6)

首先,您似乎尝试直接连接到端口5222(通常用于XMPP),但为了从客户端网页使用Strophe,您必须使用HTTP-Binding(又名BOSH)。

XMPP与BOSH

Strophe XMPP,但它的独特之处在于它实际上并不使用XMPP协议传输数据,而是依赖于BOSH(即,双向流过同步HTTP)。这是因为XMPP协议旨在始终保持客户端和服务器的连接,我们都知道这不是HTTP的工作原理。换句话说,BOSH允许您的HTTP客户端异步接收数据,而无需明确地请求它。如果您对BOSH有更多疑问,请告诉我,我会尽力解释您的需求和原因。

在连接Strophe之前,您必须在韵律中启用此功能,请查看此链接以获取设置。

Prosody Docs - Setting up BOSH

一旦您设置了BOSH,您将需要更改客户端代码以使用其他地址。您可能已将BOSH的路径+端口设置为:5280/http-bind/之类的内容。此时,您需要确保Strophe使用此URL而不是实际的X22P端口5222。

最后,您的网站域和端口之外的任何资源都需要CORS。在您的示例中,您的客户端必须向作为页面本身(Strophe和Prosody之间的连接)在不同端口+域上运行的URL发出请求。好消息是,Prosody已经支持CORS并使其非常简单。所有这些都在我之前链接的页面上进行了更详细的解释。

希望有所帮助!