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

mag*_*gos 3 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>
Run Code Online (Sandbox Code Playgroud)

作为客户,我想使用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);
    }
});
Run Code Online (Sandbox Code Playgroud)

在控制台中我看到错误:

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.
Run Code Online (Sandbox Code Playgroud)

如何在我的请求中添加Access-Control-Allow-Origin'标头?

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

XMLHttpRequest cannot load localhost:5222. Cross origin requests are only supported for HTTP.
Run Code Online (Sandbox Code Playgroud)

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

WebSocket connection to 'ws://localhost:5222/' failed: Error during WebSocket handshake: Unexpected response code: 200 
Run Code Online (Sandbox Code Playgroud)

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?
Run Code Online (Sandbox Code Playgroud)

fps*_*ton 6

首先,看起来你正试图直接连接到端口5222(通常用于XMPP),但是为了从客户端网页使用Strophe,你必须使用HTTP-Binding(又名BOSH).

XMPP与BOSH

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

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

韵律文件 - 建立BOSH

设置BOSH后,您需要更改客户端代码以使用其他地址.您可能已经为BOSH设置了路径+端口,例如:5280/http-bind/.此时,您需要确保Strophe使用此URL而不是实际的XMPP端口5222.

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

希望有所帮助!