Advertisement
Guest User

Untitled

a guest
Nov 19th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.87 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.   <title>WebSockets Client</title>  
  5.   <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  6. </head>
  7. <body>
  8. Enter text to send to the websocket server:
  9. <div id="send">
  10.     <input type="text" id="data" size="100"/><br>
  11.     <input type="button" id="sendtext" value="send text"/>
  12. </div>
  13. <div id="output"></div>
  14. </body>
  15. </html>
  16. <script>
  17.  
  18. jQuery(function($){
  19.  
  20.   if (!("WebSocket" in window)) {
  21.     alert("Your browser does not support web sockets");
  22.   }else{
  23.     setup();
  24.   }
  25.  
  26.  
  27.   function setup(){
  28.    
  29.     // Note: You have to change the host var
  30.     // if your client runs on a different machine than the websocket server
  31.    
  32.     var host = "ws://localhost:9090/ws";
  33.     var socket = new WebSocket(host);
  34.     //console.log("socket status: " + socket.readyState);  
  35.    
  36.     var $txt = $("#data");
  37.     var $btnSend = $("#sendtext");
  38.  
  39.     $txt.focus();
  40.  
  41.     // event handlers for UI
  42.     $btnSend.on('click',function(){
  43.       var text = $txt.val();
  44.       if(text == ""){
  45.         return;
  46.       }
  47.       socket.send(text);
  48.       $txt.val("");    
  49.     });
  50.  
  51.     $txt.keypress(function(evt){
  52.       if(evt.which == 13){
  53.         $btnSend.click();
  54.       }
  55.     });
  56.  
  57.     // event handlers for websocket
  58.     if(socket){
  59.  
  60.       socket.onopen = function(){
  61.         //alert("connection opened....");
  62.       }
  63.  
  64.       socket.onmessage = function(msg){
  65.         showServerResponse(msg.data);
  66.       }
  67.  
  68.       socket.onclose = function(){
  69.         //alert("connection closed....");
  70.         showServerResponse("The connection has been closed.");
  71.       }
  72.  
  73.     }else{
  74.       console.log("invalid socket");
  75.     }
  76.  
  77.     function showServerResponse(txt){
  78.       var p = document.createElement('p');
  79.       p.innerHTML = txt;
  80.       document.getElementById('output').appendChild(p);
  81.     }  
  82.  
  83.  
  84.   }
  85.  
  86.  
  87.  
  88.  
  89.  
  90. });
  91.  
  92. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement