wsapp.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var form = document.getElementById('form-msg');
  2. var cmd = document.getElementById('cmd');
  3. var listMsgs = document.getElementById('msgs');
  4. var socketStatus = document.getElementById('status');
  5. var btnClose = document.getElementById('btnClose');
  6. var wsUrl = 'ws://' + window.location.hostname + ':81';
  7. var socket = new WebSocket(wsUrl);
  8. socket.onopen = function(event) {
  9. //socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.URL;
  10. socketStatus.innerHTML = 'Connected';
  11. socketStatus.className = 'open';
  12. };
  13. socket.onerror = function(error) {
  14. console.log('WebSocket error: ' + error);
  15. };
  16. socket.onmessage = function(event) {
  17. var msg = event.data;
  18. listMsgs.innerHTML += msg;
  19. listMsgs.scrollTop = listMsgs.scrollHeight;
  20. };
  21. socket.onclose = function(event) {
  22. socketStatus.innerHTML = 'Disconnected';
  23. socketStatus.className = 'closed';
  24. };
  25. function sendCmd() {
  26. socket.send(cmd.value);
  27. listMsgs.innerHTML += 'Sent: ' + cmd.value + '\n';
  28. cmd.value = '';
  29. return false;
  30. }
  31. function togConn() {
  32. if(socketStatus.className=='open') { socket.close(); btnClose.innerHTML='Reload'; }
  33. else location.reload();
  34. }
  35. document.getElementById("cmd")
  36. .addEventListener("keyup", function(event) {
  37. event.preventDefault();
  38. if (event.keyCode === 13) {
  39. document.getElementById("btnSend").click();
  40. }
  41. });