hw_17_01_chat.html 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <header>Chat</header>
  2. <body>
  3. <div>
  4. <input id="nicknameInp" type="text"><br>
  5. <input id="messageInp" type="text"><br>
  6. <button id="sendBtn">Send</button><br><br>
  7. <div id="chat"></div>
  8. </div>
  9. <script>
  10. /*function jsonPost1(url, data) {
  11. return new Promise((resolve, reject) => {
  12. var x = new XMLHttpRequest();
  13. x.onerror = () => reject(new Error('jsonPost failed'))
  14. //x.setRequestHeader('Content-Type', 'application/json');
  15. x.open("POST", url, true);
  16. x.send(JSON.stringify(data))
  17. x.onreadystatechange = () => {
  18. if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
  19. resolve(JSON.parse(x.responseText))
  20. }
  21. else if (x.status != 200) {
  22. reject(new Error('status is not 200'))
  23. }
  24. }
  25. })
  26. }*/
  27. async function jsonPost(url, data) {
  28. var res = await fetch(url,
  29. {
  30. method: "POST",
  31. body: JSON.stringify(data)
  32. })
  33. .then(res => res.json(), () => { throw new Error('jsonPost failed') });
  34. return res;
  35. }
  36. async function getMessages(fromMessId = 0) {
  37. let a = await jsonPost("http://students.a-level.com.ua:10012", { func: "getMessages", messageId: fromMessId });
  38. nextMessageId = a.nextMessageId;
  39. if (fromMessId == 0) {
  40. chat.textContent = '';
  41. }
  42. chat.append(...a.data.map(obj => {
  43. let chatEl = document.createElement("div");
  44. let timeEl = document.createElement("div");
  45. let nickEl = document.createElement("div");
  46. let messEl = document.createElement("div");
  47. let brEl = document.createElement("br");
  48. chatEl.append(timeEl, nickEl, brEl, messEl, brEl);
  49. var date = new Date(obj.timestamp);
  50. timeEl.innerText = date.toLocaleString() + " ";
  51. nickEl.innerText = obj.nick + ": ";
  52. messEl.innerText = obj.message;
  53. return chatEl;
  54. }));
  55. }
  56. async function checkLoop(interval) {
  57. while (true) {
  58. getMessages(nextMessageId);
  59. await delay(interval);
  60. }
  61. }
  62. async function sendMessage(nick, message) {
  63. let res = await jsonPost("http://students.a-level.com.ua:10012", { func: 'addMessage', nick: nick, message: message });
  64. return res;
  65. }
  66. async function sendAndCheck(nick, message) {
  67. await sendMessage(nicknameInp.value, messageInp.value);
  68. getMessages(nextMessageId);
  69. }
  70. const delay = async (ms) => {
  71. return new Promise(res => setTimeout(res, ms));
  72. }
  73. let nextMessageId = 0;
  74. sendBtn.onclick = async () => {
  75. sendAndCheck(nicknameInp.value, messageInp.value);
  76. }
  77. checkLoop(5000);
  78. </script>
  79. </body>