Faye和Node.js:如何在服务器端运行Faye客户端?

4

我正在尝试开发一个Faye服务端客户端以需要自动运行。在Faye的官方网站上,我只找到了关于服务端客户端的文档,没有关于如何运行它的信息。 请告诉我如何操作。 谢谢。


使用 http.request 在 Node 中创建一个 HTTP 请求,以连接到 Faye 服务器。 - Raynos
3个回答

5

文档中缺少一个关键部分。看起来你需要调用client.connect()才能接收事件。

以下是对我有效的方法:

var faye = require('faye');

var client = new faye.Client('http://localhost:8000/faye');

//This was missing from the documentation
client.connect();

var subscription = client.subscribe('/foo', function(message){
    console.log("Event Received");
    console.log(message);
})

//This is optional
subscription.then(function() {
    console.log('Subscription is now active!');
});

var publication = client.publish('/foo', {text: "Hello World!"});

publication.then(function() {
    console.log('Message received by server!');
}, function(error) {
    console.log('There was a problem: ' + error.message);
});

好的,我是一个初学者,对JavaScript不是很了解。但是,require('faye')是不是意味着它需要一个名为'faye'的文件?如果是这样,从哪里获取该文件? - tyegah123

2

刚刚通过谷歌偶然发现了这个。你应该能够仅使用这段代码运行一个客户端:

var faye   = require('faye'),
    client = new faye.Client('http://example.com/faye');

client.subscribe('/some/channel', function(message) {
    // process message
});

如果您仍然遇到问题,请加入邮件列表http://groups.google.com/group/faye-users


这实际上是不起作用的。它缺少了client.connect()调用。有关详细信息,请参见我的答案。 - Micah

0
创建一个 .rb 文件,并填写以下代码。
require 'rubygems'
require 'faye'
cliv=Faye::RackAdapter.new(
  :mount => '/cliv', 
  :timeout => 25
)
cliv.listen(3000)

打开控制台并输入

ruby your_file.rb 

一旦完成,使用以下HTML创建JavaScript代码:
<script type="text/javascript" src="http://localhost:3000/faye.js"></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js'></script>
<script>
$("document").ready(function(){
  faye = new Faye.Client('http://localhost:3000/faye');
  faye.connect();
  subscribeObj = faye.subscribe("/hi", function(message) {
    $("#response").append(message.text);
    $("#content").val("");
  });

  $("#say").click(function(){
    content=$("#content").val();
    faye.publish("/hi", {text: content});
  });
});
</script>
<div id='response'></div>
<br/>
<input type='text' id='content' />
<div style='cursor:pointer;' id='say'> Say Something </div>

我认为你已经准备好了。:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接