假设我有以下示例代码(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从未收到消息。注意,这是一个示例代码。您可能认为我没有收到消息,因为客户端B在客户端A发送消息后连接,但在实际代码中,我在两个套接字打开后发布消息。
服务器端XSocketsController
正在工作,因为我正在使用它来发送服务器发送的通知。
我做错了什么?提前感谢!
看起来你把pub/sub和rpc混在一起了,但我不能确定你是否也不发布服务器端代码。
但是你用的是什么版本?3.0.6还是4.0?
一旦我知道版本,并有服务器端代码,我将编辑这个答案,并添加一个工作示例。
编辑(在3.0.6中添加示例):
刚刚用pub/sub写了一个非常简单的聊天。
h2控制器 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>
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);
}
}
}
<!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>
的问候Uffe