1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- <html>
- <head>
- <title>Melody example: chatting</title>
- </head>
- <style>
- #chat {
- text-align: left;
- background: #f1f1f1;
- width: 500px;
- min-height: 300px;
- padding: 20px;
- }
- </style>
- <body>
- <center>
- <h3>Chat</h3>
- <pre id="chat"></pre>
- <input placeholder="say something" id="text" type="text">
- </center>
- <script>
- var url = "ws://localhost:8080/ws";
- var ws = new WebSocket(url);
- var name = "Guest" + Math.floor(Math.random() * 1000);
- var chat = document.getElementById("chat");
- var text = document.getElementById("text");
- var now = function () {
- var iso = new Date().toISOString();
- return iso.split("T")[1].split(".")[0];
- };
- ws.onopen = function() {
- console.log("连接状态"+ws.readyState );
- console.log("open");
- };
- ws.onmessage = function (msg) {
- var line = now() + " " + "<" + name + "> " + msg.data + "\n";
- chat.innerText += line;
- };
- text.onkeydown = function (e) {
- if (e.keyCode === 13 && text.value !== "") {
- var msg = {
- action: "broadcast",
- query: {text: text.value},
- client_id: name,
- date: Date.now()
- };
- // Send the msg object as a JSON-formatted string.
- ws.send(JSON.stringify(msg));
- }
- };
- </script>
- </body>
- </html>
|