1

I use Primus to create a websocket server. And I use wscat command to test that server. It is able to connect to the websocket server. But the server can't receive any messages from the client. Below is the Primus code:

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");

And below is the way I tested it:

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

from the above commands you can see that the client can receive message when request the connection. But then I send a 'hello' to the server and the client doesn't receive the feedback message from server. And the server doesn't print the 'hello' message either. Is there anything wrong with my code? It seems that spark.on('data', function(data) method has no effect.

Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523

1 Answers1

0

You were throwing a spark error by not sending valid JSON data to the server.

message: 'Failed to decode incoming data: Unexpected token a in JSON at position 0'

Try this:

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);

It worked for me as shown below:

$ 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"
ficuscr
  • 6,975
  • 2
  • 32
  • 52