chat.html 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <!-- chat.html -->
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>Tornado聊天室</title>
  7. </head>
  8. <body>
  9. <h1>聊天室</h1>
  10. <hr>
  11. <div>
  12. <textarea id="contents" rows="20" cols="120" readonly></textarea>
  13. </div>
  14. <div class="send">
  15. <input type="text" id="content" size="50">
  16. <input type="button" id="send" value="发送">
  17. </div>
  18. <p>
  19. <a id="quit" href="javascript:void(0);">退出聊天室</a>
  20. </p>
  21. <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  22. <script>
  23. $(function() {
  24. // 将内容追加到指定的文本区
  25. function appendContent($ta, message) {
  26. var contents = $ta.val();
  27. contents += '\n' + message;
  28. $ta.val(contents);
  29. $ta[0].scrollTop = $ta[0].scrollHeight;
  30. }
  31. // 通过WebSocket发送消息
  32. function sendMessage() {
  33. message = $('#content').val().trim();
  34. if (message.length > 0) {
  35. ws.send(message);
  36. appendContent($('#contents'), '我说:' + message);
  37. $('#content').val('');
  38. }
  39. }
  40. // 创建WebSocket对象
  41. var ws= new WebSocket('ws://localhost:8888/chat');
  42. // 连接建立后执行的回调函数
  43. ws.onopen = function(evt) {
  44. $('#contents').val('~~~欢迎您进入聊天室~~~');
  45. };
  46. // 收到消息后执行的回调函数
  47. ws.onmessage = function(evt) {
  48. appendContent($('#contents'), evt.data);
  49. };
  50. // 为发送按钮绑定点击事件回调函数
  51. $('#send').on('click', sendMessage);
  52. // 为文本框绑定按下回车事件回调函数
  53. $('#content').on('keypress', function(evt) {
  54. keycode = evt.keyCode || evt.which;
  55. if (keycode == 13) {
  56. sendMessage();
  57. }
  58. });
  59. // 为退出聊天室超链接绑定点击事件回调函数
  60. $('#quit').on('click', function(evt) {
  61. ws.close();
  62. location.href = '/login';
  63. });
  64. });
  65. </script>
  66. </body>
  67. </html>