Guest User

Untitled

a guest
Apr 19th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. // if user is running mozilla then use it's built-in WebSocket
  2. window.WebSocket = window.WebSocket || window.MozWebSocket;
  3.  
  4. var connection = new WebSocket('wss://localhost:443', 'echo-protocol');
  5. connection.onopen = function () {
  6. // connection is opened and ready to use
  7. console.log('client opened socket');
  8. $scope.send();
  9. };
  10.  
  11. connection.onerror = function (error) {
  12. // an error occurred when sending/receiving data
  13. console.log('err: '+error);
  14. };
  15.  
  16. connection.onmessage = function (message) {
  17. // try to decode json (I assume that each message
  18. // from server is json)
  19. console.log('server response:'+message);
  20. try {
  21. var json = JSON.parse(message.data);
  22. console.log(json);
  23. } catch (e) {
  24. console.log('This doesn\'t look like a valid JSON: ',
  25. message.data);
  26. return;
  27. }
  28. // handle incoming message
  29. };
  30.  
  31. $scope.send = function() {
  32. // Tell the server this is client 1 (swap for client 2 of course)
  33. connection.send(JSON.stringify({
  34. id: "client1"
  35. }));
  36. };
  37.  
  38. });
Add Comment
Please, Sign In to add comment