1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>666666</title>
- </head>
- <body>
- 传递来的数据值cid:
- <input type="text" th:value="${cid}" id="cid"/>
- <p>【toUserId】:
- <div><input id="toUserId" name="toUserId" type="text" value="user-1"></div>
- <p>【contentText】:
- <div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
- <p>【操作】:
- <div>
- <button type="button" onclick="sendMessage()">发送消息</button>
- </div>
- </body>
- <script type="text/javascript">
- var socket;
- if (typeof (WebSocket) == "undefined") {
- console.log("您的浏览器不支持WebSocket");
- } else {
- console.log("您的浏览器支持WebSocket");
-
- var cid = document.getElementById("cid").value;
- console.log("cid-->" + cid);
- var reqUrl = "http://localhost:8080/websocket/" + cid;
- socket = new WebSocket(reqUrl.replace("http", "ws"));
-
- socket.onopen = function () {
- alert("Socket 已打开");
- console.log("Socket 已打开");
-
- };
-
- socket.onmessage = function (msg) {
- console.log("onmessage--" + msg.data);
-
- };
-
- socket.onclose = function () {
- console.log("Socket已关闭");
- };
-
- socket.onerror = function () {
- alert("Socket发生了错误");
-
- }
-
-
-
-
-
- }
- function sendMessage() {
- if (typeof (WebSocket) == "undefined") {
- console.log("您的浏览器不支持WebSocket");
- } else {
-
- var toUserId = document.getElementById('toUserId').value;
- var contentText = document.getElementById('contentText').value;
- var msg = '{"sid":"' + toUserId + '","message":"' + contentText + '"}';
- console.log(msg);
- socket.send(msg);
- }
- }
- </script>
- </html>
|