ws.ejs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <html>
  2. <head>
  3. <title>Melody example: chatting</title>
  4. </head>
  5. <style>
  6. #chat {
  7. text-align: left;
  8. background: #f1f1f1;
  9. width: 500px;
  10. min-height: 300px;
  11. padding: 20px;
  12. }
  13. </style>
  14. <body>
  15. <center>
  16. <h3>Chat</h3>
  17. <pre id="chat"></pre>
  18. <input placeholder="say something" id="text" type="text">
  19. </center>
  20. <script>
  21. var url = "ws://localhost:8080/ws";
  22. var ws = new WebSocket(url);
  23. var name = "Guest" + Math.floor(Math.random() * 1000);
  24. var chat = document.getElementById("chat");
  25. var text = document.getElementById("text");
  26. var now = function () {
  27. var iso = new Date().toISOString();
  28. return iso.split("T")[1].split(".")[0];
  29. };
  30. ws.onopen = function() {
  31. console.log("连接状态"+ws.readyState );
  32. console.log("open");
  33. };
  34. ws.onmessage = function (msg) {
  35. var line = now() + " " + "<" + name + "> " + msg.data + "\n";
  36. chat.innerText += line;
  37. };
  38. text.onkeydown = function (e) {
  39. if (e.keyCode === 13 && text.value !== "") {
  40. var msg = {
  41. action: "broadcast",
  42. query: {text: text.value},
  43. client_id: name,
  44. date: Date.now()
  45. };
  46. // Send the msg object as a JSON-formatted string.
  47. ws.send(JSON.stringify(msg));
  48. }
  49. };
  50. </script>
  51. </body>
  52. </html>