websocket.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * 创建websocket对象,并传入对应事件的回调函数
  3. * @param {*} name
  4. * @param {*} ws
  5. * @param {*} onopen
  6. * @param {*} onclose
  7. * @param {*} onerror
  8. * @param {*} onmessage
  9. */
  10. var createWebSocket = function(name,ws,onopen,onclose,onerror,onmessage){
  11. var socket = new WebSocket(ws);
  12. var int = null;
  13. socket.onopen = function(){
  14. console.log("WebSocket,建立连接成功,[" + name +"]");
  15. if(onopen){
  16. onopen();
  17. }
  18. int = setInterval(function(){
  19. send("a","");
  20. },30000);//三十秒心跳一次,防止nginx代理超时,没有用nginx可以去掉
  21. };
  22. socket.onclose = function(event){
  23. console.log("WebSocket,已关闭,[" + name +"]");
  24. if(onclose){
  25. onclose();
  26. }
  27. window.clearInterval(int);//关闭定时器
  28. };
  29. socket.onerror = function(event){
  30. console.log("WebSocket,异常,[" + name +"]");
  31. if(onerror){
  32. onerror();
  33. }
  34. };
  35. socket.onmessage = function(event){
  36. if(onmessage){
  37. onmessage(event.data);
  38. }
  39. };
  40. var send = function(type,msg){
  41. socket.send(JSON.stringify({"type":type,"message":msg}));
  42. }
  43. return {"send":send};
  44. }