我使用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',客户端没有收到来自服务器的反馈消息。并且服务器也不打印“hello”消息。我的代码有什么问题吗?似乎spark.on('data', function(data)
方法没有效果。
答案 0 :(得分:0)
通过不向服务器发送有效的JSON数据,您抛出了火花错误。
消息:'无法解码传入数据:JSON中出现意外的令牌a 在位置0'
试试这个:
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"