Advertisement
T99

websocket.js

T99
Jun 12th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var connection;
  2. var endpoint = '192.168.1.99';
  3. var port = '1200';
  4.  
  5. function onLoad() {
  6.  
  7.     if (checkWSSupport()) {
  8.        
  9.         var connection = new WebSocket(endpoint, port);
  10.        
  11.     }
  12.  
  13. }
  14.  
  15. function checkWSSupport() {
  16.    
  17.     if ('WebSocket' in window) {
  18.        
  19.         console.log("WebSockets are supported in this browser.");
  20.         return true;
  21.        
  22.     } else {
  23.        
  24.         console.log("WebSockets are NOT supported in this browser.");
  25.         return false;
  26.        
  27.     }
  28.    
  29. }
  30.  
  31. function initWebSocket(ep, p) {
  32.    
  33.     console.log("Attempting to initialize WebSocket...");
  34.    
  35.     try {
  36.        
  37.         connection = new WebSocket('ws://' + ep + ':' + p);
  38.        
  39.     } catch (error) {
  40.        
  41.         console.log("Could not initialize WebSocket...");
  42.        
  43.     }
  44.    
  45.     connection.onopen = function() { // Runs when WebSocket connection is successfully opened.
  46.        
  47.         console.log("WebSocket connection has opened...");
  48.        
  49.     };
  50.    
  51.     connection.onmessage = function(e) { // Runs when the WebSocket connection receives a frame.
  52.        
  53.         console.log("RECEIVED: " + e.data);
  54.        
  55.     }
  56.    
  57.     connection.onerror = function(error) { // Runs when the WebSocket connection errors.
  58.        
  59.         console.log("WebSocket Error: " + error.data);
  60.        
  61.     }
  62.  
  63.     connection.onclose = function() { // Runs when the WebSocket connection is closed.
  64.        
  65.         console.log("WebSocket connection has closed.");
  66.        
  67.     }
  68.    
  69. }
  70.  
  71. function reloadWebSocket() {
  72.    
  73.     console.log("Reloading WebSocket...");
  74.     connection = null;
  75.     initWebSocket(endpoint, port);
  76.    
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement