wsc2.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. var wsc2={
  2. url : 'ws://127.0.0.1:9999',
  3. ws:null,
  4. is_onlien:false,
  5. timer_ping:null,
  6. timer_close:null,
  7. interval_ping:10000,
  8. interval_close:5000,
  9. init:function(){
  10. var self=this;
  11. self.ws= new WebSocket(self.url);
  12. self.ws.onopen = function(evt) {
  13. console.log("Connection open ...");
  14. self.is_onlien=true;
  15. self.ws.send("client connect success");
  16. start_heartbeat();
  17. };
  18. self.ws.onmessage = function(evt) {
  19. if(evt.data=="ping"){
  20. self.send("pong");
  21. console.log("on ping");
  22. }
  23. else if(evt.data=="pong"){
  24. console.log("on pong");
  25. }
  26. else{
  27. console.log( "Received Message: " + evt.data);
  28. }
  29. clearTimeout(self.timer_close);
  30. clearTimeout(self.timer_ping);
  31. start_heartbeat();
  32. };
  33. self.ws.onclose = function(evt) {
  34. console.log("Connection closed.");
  35. };
  36. self.ws.onerror=function(evt){
  37. console.log(evt);
  38. };
  39. function start_heartbeat(){
  40. self.timer_ping=setTimeout(function(){
  41. self.send("ping");
  42. self.timer_close=setTimeout(function(){
  43. self.ws.close();
  44. self.is_onlien=false;
  45. on_offline();
  46. },self.interval_close);
  47. },self.interval_ping);
  48. };
  49. function on_offline(){
  50. }
  51. },
  52. send:function(data){
  53. this.ws.send(data);
  54. },
  55. }