index.jsp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6. <!DOCTYPE HTML>
  7. <html>
  8. <head>
  9. <title>My WebSocket</title>
  10. </head>
  11. <body>
  12. Welcome<br/>
  13. <input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
  14. <div id="message">
  15. </div>
  16. </body>
  17. <script type="text/javascript">
  18. var websocket = null;
  19. //判断当前浏览器是否支持WebSocket
  20. if('WebSocket' in window){
  21. websocket = new WebSocket("ws://localhost:8081/websocket/1");
  22. // websocket = new WebSocket("wss://wxapi.ai160.com/efunbox-edu-api-weixin/websocket/1111");
  23. }
  24. else{
  25. alert('Not support websocket')
  26. }
  27. //连接发生错误的回调方法
  28. websocket.onerror = function(){
  29. setMessageInnerHTML("error");
  30. };
  31. //连接成功建立的回调方法
  32. websocket.onopen = function(event){
  33. setMessageInnerHTML("open");
  34. }
  35. //接收到消息的回调方法
  36. websocket.onmessage = function(event){
  37. setMessageInnerHTML(event.data);
  38. }
  39. //连接关闭的回调方法
  40. websocket.onclose = function(){
  41. setMessageInnerHTML("close");
  42. }
  43. //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  44. window.onbeforeunload = function(){
  45. websocket.close();
  46. }
  47. //将消息显示在网页上
  48. function setMessageInnerHTML(innerHTML){
  49. document.getElementById('message').innerHTML += innerHTML + '<br/>';
  50. }
  51. //关闭连接
  52. function closeWebSocket(){
  53. websocket.close();
  54. }
  55. //发送消息
  56. function send(){
  57. var message = document.getElementById('text').value;
  58. websocket.send(message);
  59. }
  60. </script>
  61. </html>