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.
You were throwing a spark error by not sending valid JSON data to the server.
Try this:
It worked for me as shown below: