JavaScript WebSocket Connection to C# server


SUBMITTED BY: Guest

DATE: Nov. 24, 2014, 2:13 p.m.

FORMAT: Text only

SIZE: 1.2 kB

HITS: 943

  1. var start = function()
  2. {
  3. var inc = document.getElementById('incoming');
  4. var wsImpl = window.WebSocket || window.MozWebSocket;
  5. var form = document.getElementById('sendForm');
  6. var input = document.getElementById('sendText');
  7. inc.innerHTML += "Connecting to server..<br>";
  8. window.ws = new wsImpl('ws://' + location.hostname + ':509/');
  9. //when a message is recived
  10. ws.onmessage = function (evt)
  11. {
  12. inc.innerHTML += 'Recived< ' + evt.data + '<br>';
  13. }
  14. //when a connection is established
  15. ws.onopen = function()
  16. {
  17. inc.innerHTML += '..connection opened <br>';
  18. }
  19. //when the connection is closed
  20. ws.onclose = function()
  21. {
  22. inc.innerHTML += '..connection closed <br>';
  23. }
  24. form.addEventListner('submit', function(e)
  25. {
  26. e.preventDefault();
  27. var val = input.value;
  28. ws.send(val);
  29. input.value = "";
  30. });
  31. }
  32. function send()
  33. {
  34. var val = document.getElementById('sendText').value;
  35. ws.send(val);
  36. inc.innerHTML += 'Sent-> ' + val + '<br>';
  37. }
  38. //call the above created function on page start
  39. window.onload = start;

comments powered by Disqus