Home  >  Article  >  Web Front-end  >  基于 WebSocket 构建跨浏览器的实时应用

基于 WebSocket 构建跨浏览器的实时应用

WBOY
WBOYOriginal
2016-05-17 09:08:221509browse
        Socket.IO 是一个功能非常强大的框架,能够帮助你构建基于 WebSocket 的跨浏览器的实时应用。支持主流浏览器,多种平台,多种传输模式,还可以集合 Exppress 框架构建各种功能复杂的实时应用。

基于 WebSocket 构建跨浏览器的实时应用


使用示例


1、使用 Node HTTP 服务器


服务端示例代码:


var app = require('http').createServer(handler)

  , io = require('socket.io').listen(app)

  , fs = require('fs')

 

app.listen(80);

 

function handler (req, res) {

  fs.readFile(__dirname + '/index.html',

  function (err, data) {

    if (err) {

      res.writeHead(500);

      return res.end('Error loading index.html');

    }

 

    res.writeHead(200);

    res.end(data);

  });

}

 

io.sockets.on('connection', function (socket) {

  socket.emit('news', { hello: 'world' });

  socket.on('my other event', function (data) {

    console.log(data);

  });

});

客户端示例代码:


  var socket = io.connect('http://localhost');

  socket.on('news', function (data) {

    console.log(data);

    socket.emit('my other event', { my: 'data' });

  });


2、使用 Express 3 框架


服务端示例代码:


var app = require('express')()

  , server = require('http').createServer(app)

  , io = require('socket.io').listen(server);

 

server.listen(80);

 

app.get('/', function (req, res) {

  res.sendfile(__dirname + '/index.html');

});

 

io.sockets.on('connection', function (socket) {

  socket.emit('news', { hello: 'world' });

  socket.on('my other event', function (data) {

    console.log(data);

  });

});


客户端示例代码:

  var socket = io.connect('http://localhost');

  socket.on('news', function (data) {

    console.log(data);

    socket.emit('my other event', { my: 'data' });

  });

 


支持的传输


为了给各个不同的浏览器提供实时连接,Socket.IO 选择在运行时会自动最有能力的运输模式,不影响 API 的使用。


  • WebSocket
  • Adobe Flash Socket
  • AJAX 长轮询
  • AJAX 多重流
  • iframe
  • JSONP 轮询


支持的浏览器

桌面端

  • Internet Explorer 5.5+
  • Safari 3+
  • Google Chrome 4+
  • Firefox 3+
  • Opera 10.61+


移动端

  • iPhone Safari
  • iPad Safari
  • Android WebKit
  • WebOs WebKit

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn