index.html 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <!DOCTYPE html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>websocket demo</title>
  5. <meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <style>
  7. .row {
  8. margin: 1rem
  9. }
  10. </style>
  11. </head>
  12. <body> <a class="btn btn-info" href="\fun"><span class="glyphicon glyphicon-home"></span>&nbsp;返回</a>
  13. <div class='row'>发送方:
  14. <select id='sender'>
  15. <option value="Bob" selected>Bob</option>
  16. <option value="Alice">Alice</option>
  17. <option value="Jack">Jack</option>
  18. </select>
  19. </div>
  20. <div class='row'>接收方:
  21. <select id='receiver'>
  22. <option value="Bob">Bob</option>
  23. <option value="Alice" selected>Alice</option>
  24. <option value="Jack">Jack</option>
  25. </select>
  26. </div>
  27. <textarea id='msg' class='row' rows="10" cols="30"></textarea>
  28. <div class='row'>
  29. <button id='sendBtn'>发送</button>
  30. </div>
  31. <h3 class='row'>收到的消息:</h3>
  32. <div id='conversation' class='row'></div>
  33. <script>
  34. var sender = document.getElementById('sender');
  35. var receiver = document.getElementById('receiver');
  36. var conversation = document.getElementById('conversation');
  37. var sendBtn = document.getElementById('sendBtn');
  38. var socket = null;
  39. var createSocket = function () {
  40. if (socket) {
  41. socket.close();
  42. }
  43. var url = 'ws://' + window.location.host + '/ws/' + sender.options[sender.selectedIndex].value;
  44. socket = new WebSocket(url);
  45. socket.onopen = function () {
  46. console.log('connected to ' + url);
  47. }
  48. socket.onmessage = function (event) {
  49. var data = JSON.parse(event.data);
  50. conversation.innerHTML = conversation.innerHTML + data.from + ':' + data.content + '<br/>';
  51. }
  52. socket.onclose = function () {
  53. console.log('close connect to' + url);
  54. }
  55. };
  56. var sendMessage = function () {
  57. var msg = document.getElementById('msg').value;
  58. var bd = JSON.stringify({
  59. from: sender.options[sender.selectedIndex].value,
  60. content: msg,
  61. to: receiver.options[receiver.selectedIndex].value
  62. })
  63. console.log(bd)
  64. fetch('/rest/message', {
  65. method: 'POST',
  66. headers: {
  67. 'Content-type': 'application/json',
  68. },
  69. body: bd
  70. }).then(res => res.json()).then(data => {
  71. if (!data.succeed) {
  72. alert(data.msg);
  73. }
  74. })
  75. };
  76. sender.onchange = function () {
  77. createSocket();
  78. }
  79. sendBtn.onclick = function () {
  80. sendMessage();
  81. }
  82. createSocket();
  83. </script>
  84. </body>