2012-03-16 100 views
0

我想獲取系統通知並將它們通過http傳遞給客戶端。將兩個主循環合併爲一個node.js進程

現在我使用node.js在一個進程中提供這兩個服務,但存在一個問題。 通知監聽器有自己的主循環監聽系統事件,當服務啓動時,它使服務器停止提供http服務。我認爲如果我能將這兩種服務的主要環路合併爲一個,問題就可以解決。這可能嗎?我怎麼能開始?

謝謝

下面是示例代碼:

var server = require("express").createServer(), 
    io = require('socket.io').listen(server); 

server.listen(8000); 
server.get("/", function (req, res) { 
    res.sendfile("./public/main.html"); 
}); 
io.of('/images').on('connection', function (socket) { 
    //read images and transfer 
} 
io.of('/notify').on('connection', function (socket) { 
    //start listen system notifications 
    notifyLib.start_daemon(); 
} 

「notifyLib.start_daemon()」 是一個原生擴展其代碼如下:

DBusError error; 
int rt; 

dbus_error_init (&error); 
connection = dbus_bus_get (DBUS_BUS_SESSION, &error); 
if (dbus_bus_name_has_owner(connection, DBUS_NAME, &error)) 
    printf("*** DBUS_NAME had owner\n"); 
rt = dbus_bus_request_name (connection, DBUS_NAME, 0, &error); 
if (!dbus_connection_add_filter (connection, filter_func, NULL, NULL)) 
    printf("*** Failed to add filter\n"); 
if (!dbus_connection_register_object_path (connection, DBUS_PATH, &echo_vtable, (void*) 0xdeadbeef)) 
    printf("*** Failed to register object path\n"); 
while (dbus_connection_read_write_dispatch (connection, -1)) 
    ; 
dbus_connection_remove_filter (connection, filter_func, NULL); 
dbus_connection_unref (connection); 
dbus_shutdown(); 

有有很多圖像需要傳輸,但是當聽者啓動時,圖像傳輸將停止。

+0

你能提供一些代碼嗎? – Magic 2012-03-16 07:20:57

+0

我在帖子中添加了示例代碼。 – Bruce 2012-03-16 10:27:59

+0

這很難理解你的意思。你在阻止服務器的'/ notify'連接處理程序中做了些什麼?如果是這樣,你應該提供源代碼。你上面有什麼看起來很好。 – 2012-03-16 10:41:48

回答

0

希望我明白你的問題。

最簡單的解決方案是使用Cluster

由於叉幾個進程來處理該請求。

+0

感謝您的幫助。我使用child_process.fork()作爲解決方法。我猜在notifyLib.start_daemon()中提供了dbus服務的while循環阻塞了服務器。通過使用child_process.fork(),系統中有兩個節點進程。我最初試圖做的是將此循環集成到node.js事件循環中。所以在服務器運行時只需要一個進程。 – Bruce 2012-03-20 01:19:24

0

從節點,你可以做一個計時器來調用dbus_connection_read_write_dispatch()?

然後,您可以刪除while()循環。

你必須將dbus清理代碼移動到它自己的函數中,當你完成處理DBus時,節點可以調用它。

https://nodejs.org/en/docs/guides/timers-in-node/