socket1.html 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  1. <script>
  2. var socket;
  3. if(typeof(WebSocket) == "undefined") {
  4. console.log("您的浏览器不支持WebSocket");
  5. }else{
  6. console.log("您的浏览器支持WebSocket");
  7. //实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
  8. socket = new WebSocket("ws://localhost:8080/websocket/[[${pageNumber}]]/[[${functionNumber}]]/[[${socketConfigMapId}}]]");
  9. //等同于socket = new WebSocket("/checkcenter/websocket/[[${cid}]]".replace("http","ws"));
  10. //打开事件
  11. socket.onopen = function() {
  12. console.log("Socket 已打开");
  13. //socket.send("这是来自客户端的消息" + location.href + new Date());
  14. };
  15. //获得消息事件
  16. socket.onmessage = function(msg) {
  17. console.log(msg.data);
  18. //发现消息进入 开始处理前端触发逻辑
  19. };
  20. //关闭事件
  21. socket.onclose = function() {
  22. console.log("Socket已关闭");
  23. };
  24. //发生了错误事件
  25. socket.onerror = function() {
  26. alert("Socket发生了错误");
  27. //此时可以尝试刷新页面
  28. }
  29. //离开页面时,关闭socket
  30. //jquery1.8中已经被废弃,3.0中已经移除
  31. // $(window).unload(function(){
  32. // socket.close();
  33. //});
  34. }
  35. </script>