0

假设我有以下示例代码(JavaScript):

// Client A 
var conn = new XSockets.WebSocket([wsUri]);

conn.on(XSockets.Events.open, function (clientInfo) {
    conn.publish("some:channel", { text: "hello world" });
});

// Client B (subscriber) 
var conn = new XSockets.WebSocket([wsUri]);

conn.on(XSockets.Events.open, function (clientInfo) {
    conn.on("some:channel", function(message) {
        // Subscription receives no message!
    });
});

客户端 B永远不会收到消息。请注意,这是一个示例代码。您可能认为我没有收到消息,因为在客户端 A 发送消息后客户端 B已连接,但在实际代码中,我在打开两个套接字后发布消息。

服务器端正XSocketsController在工作,因为我将它用于服务器发送的通知。

我究竟做错了什么?先感谢您!

4

1 回答 1

2

看起来您已将 pub/sub 与 rpc 混为一谈,但我无法确定您是否也发布了服务器端代码。

但是你用的是什么版本?3.0.6 还是 4.0?

一旦我知道版本并拥有服务器端代码,我将编辑此答案并添加一个工作示例。

编辑(为 3.0.6 添加示例):

刚刚用 pub/sub 写了一个非常简单的聊天。

控制器

using XSockets.Core.Common.Socket.Event.Interface;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;

namespace Demo
{
    public class SampleController : XSocketController
    {
        /// <summary>
        /// By overriding the onmessage method we get pub/sub
        /// </summary>
        /// <param name="textArgs"></param>
        public override void OnMessage(ITextArgs textArgs)
        {
            //Will publish to all client that subscribes to the value of textArgs.@event            
            this.SendToAll(textArgs);
        }
    }
}

HTML/JavaScript

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-2.1.1.js"></script>
    <script src="Scripts/XSockets.latest.min.js"></script>

    <script>
        var conn;

        $(function() {
            conn = new XSockets.WebSocket('ws://127.0.0.1:4502/Sample');

            conn.onopen = function(ci) {
                console.log('open', ci);
                conn.on('say', function(d) {
                    $('div').prepend($('<p>').text(d.text));
                });
            }

            $('input').on('keydown', function(e) {
                if (e.keyCode == 13) {
                    conn.publish('say', { text: $(this).val() });
                    $(this).val('');
                }
            });
        });
    </script>
</head>
<body>
    <input type="text" placeholder="type and hit enter to send..."/>    
    <div></div>
</body>
</html>

问候乌夫

于 2014-07-06T12:27:48.583 回答