index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env node
  2. var WebSocketServer = require('websocket').server;
  3. var http = require('http');
  4. var server = http.createServer(function(request, response) {
  5. console.log((new Date()) + ' Received request for ' + request.url);
  6. response.writeHead(404);
  7. response.end();
  8. });
  9. server.listen(8011, function() {
  10. console.log((new Date()) + ' Server is listening on port 8011');
  11. });
  12. wsServer = new WebSocketServer({
  13. httpServer: server,
  14. // You should not use autoAcceptConnections for production
  15. // applications, as it defeats all standard cross-origin protection
  16. // facilities built into the protocol and the browser. You should
  17. // *always* verify the connection's origin and decide whether or not
  18. // to accept it.
  19. autoAcceptConnections: false
  20. });
  21. function originIsAllowed(origin) {
  22. // put logic here to detect whether the specified origin is allowed.
  23. return true;
  24. }
  25. wsServer.on('request', function(request) {
  26. if (!originIsAllowed(request.origin)) {
  27. // Make sure we only accept requests from an allowed origin
  28. request.reject();
  29. console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
  30. return;
  31. }
  32. var connection = request.accept('arduino', request.origin);
  33. console.log((new Date()) + ' Connection accepted.');
  34. connection.on('message', function(message) {
  35. if (message.type === 'utf8') {
  36. console.log('Received Message: ' + message.utf8Data);
  37. // connection.sendUTF(message.utf8Data);
  38. }
  39. else if (message.type === 'binary') {
  40. console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
  41. //connection.sendBytes(message.binaryData);
  42. }
  43. });
  44. connection.on('close', function(reasonCode, description) {
  45. console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
  46. });
  47. connection.sendUTF("Hallo Client!");
  48. });