simple-protocol.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var nssocket = require('../lib/nssocket');
  2. //
  3. // define a simple message protocol as [<type>, <id>] and create some messages that use it.
  4. //
  5. var message1 = ['message', 'one'];
  6. var message2 = ['message', 'two'];
  7. //
  8. // Create an `nssocket` TCP server and tell the server to listen on port `6785`.
  9. //
  10. var server = nssocket.createServer(function (socket) {
  11. //
  12. // Here `socket` will be an instance of `nssocket.NsSocket`.
  13. // When there is a connection, send `message1` to the socket.
  14. //
  15. socket.send(message1);
  16. //
  17. // listen for `message2` from the connecting socket.
  18. //
  19. socket.data(message2, function (data) {
  20. //
  21. // If this callback is called, we know that the socket
  22. // speaks our language, we will likely be provided with
  23. // a payload. In this case `{ "foo": "bar" }`.
  24. //
  25. console.dir(data);
  26. })
  27. }).listen(6785);
  28. //
  29. // Create a new `nssocket` instance and then connect to the server in 1000 miliseconds.
  30. //
  31. setTimeout(function() {
  32. var outbound = new nssocket.NsSocket();
  33. //
  34. //
  35. //
  36. outbound.data(message1, function () {
  37. outbound.send(message2, { "foo": "bar" });
  38. });
  39. outbound.connect(6785);
  40. }, 1000);