Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. <html>
  2. <title>GU Websocket Example</title>
  3. <head>
  4.  
  5. <script>
  6.  
  7. // Check if the browser supports Websockets
  8. if (window.WebSocket){
  9. console.log("This browser supports websockets.");
  10. } else {
  11. console.log("This browser does not support websockets.");
  12. }
  13.  
  14. // Define the host
  15. var host = 'ws://staging.socket.gooduncle.com';
  16.  
  17. // Establish a connection
  18. var ws = new WebSocket(host);
  19.  
  20. // Bind to the onopen event if needed
  21. ws.onopen = function(e){
  22. console.log('The socket is open');
  23. };
  24.  
  25. // Bind to any errors experienes
  26. ws.onerror = function(e){
  27. console.log('The socket is experiencing an error');
  28. };
  29.  
  30. // Bind to the onclose event if needed
  31. // Note: Dont depend on this method, its unreliable.
  32. ws.onclose = function(e){
  33. console.log('The socket is closed');
  34. };
  35.  
  36.  
  37. // Send a single unicode character every 300ms
  38. var _keepAlive = function(){
  39. ws.send('`');
  40. };
  41. var foo = setInterval(_keepAlive, 300);
  42.  
  43. // Sample logic for detecting faulty connections
  44. var lastReceivedMessage = Date.now();
  45.  
  46. // Bind to the onmessage event
  47. ws.onmessage = function(e) {
  48. console.log('Received message',e.data);
  49. lastReceivedMessage = Date.now();
  50. };
  51.  
  52. // Every second, check if the connection is faulty.
  53. var _loop = function(){
  54. var elapsed = Date.now() - lastReceivedMessage;
  55. if(elapsed > 3000){
  56. console.log("The connection is probably dead");
  57. } else {
  58. if(elapsed > 1000){
  59. console.log("The connection is faulty");
  60. } else {
  61. console.log("Everythings fine");
  62. }
  63. }
  64. };
  65. var bar = setInterval(_loop, 1000);
  66.  
  67.  
  68. </script>
  69. </head>
  70. <body>
  71. <p>Open the inspector and view the console logs.</p>
  72. </body>
  73. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement