如何创建sockjs(SockJS - WebSocket仿真)或Shoe独立服务器(node.js)?

时间:2013-12-23 01:41:13

标签: node.js sockjs dnode

有谁知道如何创建sockjs-node(SockJS - WebSocket仿真)或Shoe独立服务器?

没有http服务器可以装箱吗?

只需要与dnode交换数据,并且不需要静态页面。

例如,当我在节点服务器端执行时:

var shoe = require('shoe');
var dnode = require('dnode');
var http = require('http');


var server = http
    .createServer()
    .listen(9999);

var echo = shoe
    .createServer()
    .on('connection', function(c)
    {
        var d = dnode(
        {
            test: function()
            {
                console.log('--------');
            }
        });

        c
            .on('data', function(message)
            {
                c.write(message);
            })
            .on('close', function() {});

        c
            .pipe(d)
            .pipe(c);

        c.on('close', function() {});
    })
    .installHandlers(server,
    {
        prefix: '/dnode'
    });

以下代码(客户端)

var d = dnode()
    .on('remote', function(remote)
    {
        remote.test();
    });

d
    .pipe(shoe('http://localhost/dnode'))
    .pipe(d);

因以下错误而失败:(Chrome)

GET http://localhost/dnode/info  app.bundle.js:14681
AbstractXHRObject._start app.bundle.js:14681
(anonymous function)

1 个答案:

答案 0 :(得分:0)

找不到使用SockJS或Shoe的方法,所以我换了websocket-stream

这是一个有效的代码:

节点服务器

'use strict';

var ws = require('ws');
var websocketStream = require('websocket-stream');
var dnode = require('dnode');
var http = require('http');

var HTTPserver = http
    .createServer()
    .listen(9999);

var WSserver = new ws.Server(
{
    server: HTTPserver
});

WSserver
    .on('connection', function(s)
    {
        var c = websocketStream(s);
        var d = dnode(
        {
            test: function(f)
            {
                console.log('--------');
                f('hello');
            }
        });

        c
            .pipe(d)
            .pipe(c);
    });

浏览器客户端

'use strict';

var websocketStream = require('websocket-stream');
var dnode = require('dnode');

var c = websocketStream('ws://localhost:9999');
var d = dnode()
    .on('remote', function(remote)
    {
        remote.test(function(msg)
        {
            alert(msg);
        });
    });

c
    .pipe(d)
    .pipe(c);