A library to make working with websockets easier.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 1.5KB

8 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # SockSugar
  2. SockSugar is a rather simple library to simplify working with WebSockets. It makes WebSockets work somewhat like regular HTTP requests.
  3. ## Usage
  4. ### Requests
  5. Requests resemble HTTP requests, where the client send data to the server and wait for a response.
  6. On the server side:
  7. var SockSugar = require("socksugar");
  8. var server = new SockSugar({
  9. port: 8081
  10. });
  11. server.on("connection", function(socket) {
  12. console.log("Connection!");
  13. socket.on("request", function(req) {
  14. console.log("Request for "+req.url);
  15. console.log(req.data);
  16. req.reply({
  17. msg: "No."
  18. });
  19. });
  20. });
  21. On the client side:
  22. var sock = new SockSugar("ws://example.com");
  23. sock.on("ready", function() {
  24. sock.send("hi", {
  25. msg: "Hi!"
  26. }, function(err, data) {
  27. console.log(data);
  28. }
  29. });
  30. The server side console will say:
  31. Connection!
  32. Request for hi
  33. { msg: 'Hi!' }
  34. The client side console will say:
  35. { msg: 'No.' }
  36. ### Events
  37. Unlike HTTP, the server can push data to the client. Here's a simple example, where writing something in the console will emitt an event to all connected clients and displayed with alert().
  38. On the server side:
  39. var SockSugar = require("socksugar");
  40. var server = new SockSugar({
  41. port: 8081
  42. });
  43. process.stdin.on("data", function(data) {
  44. var str = data.toString("utf8");
  45. server.socks.forEach(function(sock) {
  46. sock.send("myEvent", {
  47. msg: str
  48. });
  49. });
  50. });
  51. On the client side:
  52. var sock = new SockSugar("ws://example.com");
  53. sock.on("myEvent", function(data) {
  54. alert(data.msg);
  55. });