test.html 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <html>
  2. <head>
  3. <meta charset="UTF-8">
  4. <title>websocket测试</title>
  5. <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  6. <style type="text/css">
  7. h3,h4{
  8. text-align:center;
  9. }
  10. </style>
  11. </head>
  12. <body>
  13. <h3>WebSocket测试,客户端接收到的消息如下:</h3>
  14. <textarea id = "messageId" readonly="readonly" cols="150" rows="30" >
  15. </textarea>
  16. <script type="text/javascript">
  17. var socket;
  18. if (typeof (WebSocket) == "undefined") {
  19. console.log("遗憾:您的浏览器不支持WebSocket");
  20. } else {
  21. console.log("恭喜:您的浏览器支持WebSocket");
  22. //实现化WebSocket对象
  23. //指定要连接的服务器地址与端口建立连接
  24. //注意ws、wss使用不同的端口。我使用自签名的证书测试,
  25. //无法使用wss,浏览器打开WebSocket时报错
  26. //ws对应http、wss对应https。
  27. socket = new WebSocket("ws://localhost:8889/plag");
  28. //连接打开事件
  29. socket.onopen = function() {
  30. console.log("Socket 已打开");
  31. socket.send('plag:{"fileId":16,"baseFileId":10,"fileType":1,"algorithmId":1,"params":null,"sessionId":"0"}');
  32. };
  33. //收到消息事件
  34. socket.onmessage = function(msg) {
  35. $("#messageId").append(msg.data+ "\n");
  36. console.log(msg.data );
  37. };
  38. //连接关闭事件
  39. socket.onclose = function() {
  40. console.log("Socket已关闭");
  41. };
  42. //发生了错误事件
  43. socket.onerror = function() {
  44. alert("Socket发生了错误");
  45. }
  46. //窗口关闭时,关闭连接
  47. window.unload=function() {
  48. socket.close();
  49. };
  50. }
  51. </script>
  52. </body>
  53. </html>