學習小筆記---socket.io 淺講

// Teambition


socket.io 

協作應用:(要求很好的同步性,reload,穩定性要高,要前後端剝離)

1、信息不能出現不對稱,實時同步應用

2、討論有明確的上下文,能夠針對特定對象更新數據

3、應用能夠持續運行,緩存必要數據根據網絡情況進行必要操作


Server -> App (多個)


Socket.io

1、旨在在不用版本的瀏覽器(包括移動設別瀏覽器在內)間實現實時通信

2、在多種傳輸方式中自動選擇最優方式

3、100% JavaScript 


傳輸方式:(性能從強到弱)   // http://socket.io/#browser-support

WebSocket

Adobe Flash Socket

AJAX long polling

AJAX multipart streaming

Forever iframe

JSONP Polling


安裝socket

$npm install socket.io
app = require('http').createServer( handler )
io = require('socket.io').listen( app )
fs = require('fs')
app.listen(80)
io.socket.on 'connection',(socket) -> ...



前端的類:

<script src="/socket.io/socket.io.js"></script>
socket = io.connect('http://localhost')
socket.on 'eventName',(data)->...



接口:

1、發送事件

socket.emit 'eventName',{data}


2、響應事件

socket.on 'eventName',(data)->...


客戶端發起請求

cid = (new Data).getValue()
socket.emit 'eventName',{
cid:cid
...
}
socket.once "eventName#{cid}",(data)->...



搭建MV*應用

Backbone                 // http://backbonejs.org

TodoMVC// http://todomvc.com


以Backbone框架爲例

實時更新前端數據 

class NewModel extends Backbone.Model
initialize: ->
    @listen() if @id
    ...
listen: ->
    socket.on ":change:#{@id}",(changes) =>//change事件
    @set(changes)
    ...



根據數據變化更新視圖

class NewModel extends Backbone.Model
initialize: (model) ->
    @model = model
    @render()
    @listen() if @model.id
    ...
listen: ->
    @listenTo(@model,'change',@render)
    ...
render: ->
    @$el.html(Template(@model.toJSON()))
    ...



網絡狀況處理

SOCKET.connect host,{]}



例子:

SOCKET.connect = (host, option) ->
    unless host and window.io and (typeof window.io.connect is 'funciton')
        return false
    _connect = =>
        @socket.once("#{@eventName}.connect"),(response) =>
            return @onError(response.error) if response.error
            @connectCount++
            if @connectCount is 1
                return @option.onConnect(response.data)
            else
                return @option.onReconnect(response.data)
        )
    _disconnect = =>
        return @option.onDisconnect()
    @options = _.extend(@options, options)
    @eventName = @options.eventName if @options.eventName
    @socket = window.io.connect(host)
    @socket.on('connect', _connect)
    @socket.on('disconnect', _disconnect)
    @socket.on('error', (err) => @options.onError(err))



瞭解更多// github.com/teambition/socket.io-hub

使用Room和Broadcase來簡化多客戶端同步

socket.io的性能瓶頸主要在併發消息數量

通過運行多個服務器實例來提高承載能力

使用YO進行框架搭建

使用RequireJS進行包管理

使用Grunt進行任務管理




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章