1

我使用 Primus 创建一个 websocket 服务器。我使用 wscat 命令来测试该服务器。它能够连接到 websocket 服务器。但是服务器无法接收来自客户端的任何消息。以下是 Primus 代码:

http = require('http');
server = http.createServer();

Primus = require('primus');
primus = new Primus(server, {
  transformer: 'websockets',
  pathname: 'ws'
});

primus.on('connection', function connection(spark) {
  console.log("client has connected");
  spark.write("Herro Client, I am Server");
  spark.on('data', function(data) {
    console.log('PRINTED FROM SERVER:', data);
    spark.write('receive '+data)
  });

});

server.listen(5431);
console.log("Server has started listening");

下面是我测试它的方式:

$ wscat -c  http://localhost:5431/ws
connected (press CTRL+C to quit)
< "Herro Client, I am Server"
> hello
> 

从上面的命令你可以看到客户端可以在请求连接时收到消息。但是后来我向服务器发送了一个“你好”,而客户端没有收到来自服务器的反馈消息。服务器也不打印“hello”消息。我的代码有什么问题吗?该spark.on('data', function(data)方法似乎没有效果。

4

1 回答 1

0

您因未向服务器发送有效的 JSON 数据而引发了 spark 错误。

消息:“无法解码传入数据:JSON 中位置 0 的意外标记 a”

尝试这个:

http = require('http');
server = http.createServer();

Primus = require('primus');
primus = new Primus(server, {
  transformer: 'websockets',
  pathname: 'ws'
});


primus.on('initialised', function() {
    console.log('Primus Initialized.');
});

primus.on('connection', function connection(spark) {
  console.log("client has connected");

  spark.write("Herro Client, I am Server");

  spark.on('data', function(data) {
    console.log('PRINTED FROM SERVER:', data);
    spark.write('received');
  });

  spark.on('heartbeat', function() {
    console.log('hearbeat...');
  });


  //happens after primus.disconnection
  spark.on('end', function() {
    console.log('spark end');
  });

  spark.on('error', function (v) {
    console.log('spark error', v);
  });

});

//happens before spark.end
primus.on('disconnection', function (spark) {
    console.log('primus disconnection');
});

primus.on('error', function error(err) {
    console.log('primus error', err.stack);
});

server.listen(5431);

它对我有用,如下所示:

$ wscat -c 127.0.0.1:5431/ws/websocket
connected (press CTRL+C to quit)
< "Herro Client, I am Server"
> {"a":"b"}
< "received"
> {"valid":"json"}
< "received"
于 2017-05-03T22:34:21.580 回答