GithubHelp home page GithubHelp logo

serverpush's Introduction

Server Push

服务器推送数据的几种方式:ajax轮询,comet,websocket,server send event。

一、WebSocket

  var ws = new WebSocket('ws://127.0.0.1:8001');

  ws.onopen = function(e){
      console.log("连接服务器成功");
      ws.send("连接服务器成功:hello server");
  }
  ws.onclose = function(e){
      console.log("服务器关闭");
  }
  ws.onerror = function(){
      console.log("连接出错");
  }

  ws.onmessage = function(e){
    console.info(e.data);
  }

二、Server Send Event

var source = new EventSource("stream");
        
    // 如果Server不指定event事件类型,则调用默认的onmessage回调
    source.onmessage=function(e) {
      console.info(e.data);
    };

   // 接受connectiontime事件消息,自定义
    source.onconnecttime=function(e) {
      console.info(e.data);
    };

    // 打开连接
    source.onopen=function(event) {
      console.info("打开连接");
    };

   // 关闭连接
   source.onerror=function(event) {
      if (event.target.readyState === EventSource.CLOSED) {
        source.close();
        console.info("链接关闭");
      } else if (event.target.readyState === EventSource.CONNECTING) {
        console.info("连接关闭,尝试重新链接!");
      } else {
        console.info(""连接关闭,未知错误");
      }
    };

serverpush's People

Contributors

mircode avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.