18
淺談Socket.IO MiCloud - Simon

Node.js 淺談socket.io

Embed Size (px)

Citation preview

淺談Socket.IOMiCloud - Simon

大綱

● SocketIO的歷史與發展

● Node.js的SocketIO套件介紹

○ Server Socket○ Client Socket

● 第一個SocketIO實作

● SocketIO範例演示 - SocketIO Talk

Communicate between Server to Client

<hr/><div id="tt">----</div><hr/>

setInterval(function(){ $('#tt').html( new Date() );}, 1000);

古早的作法 - Polling (輪循)

Client Server

DATA

HEADER

古早的作法 - Comet

HTML5 - WebSocket

● WebSocket是HTML5開始提供的一種瀏覽器

與伺服器間進行全雙工通訊的網路技術

● WebSocket通訊協定於2011年被IETF定為標

準 RFC 6455,WebSocketAPI被W3C定為標

準。

Browser支援(wikipedia)

● Google Chrome:Chrome 4 及之後的版本都支援websocket,版本14開始支援Version 13協定。

● Safari:iOS4 以及 5 上的safari使用的舊版的WebSocket;iOS 6開始支援Version 13

● Mozilla Firefox:版本4之後支援websocket,版本6開始支援Version 13。

● Opera:Opera 10.7和11.0的預覽版本中也支援了websocket。

● Internet Explorer:從版本10開始支援WebSocket。

First SocketIO AppServer

Client

單獨啟動SocketIO Server的方式

透過emit發送訊息至client端

監聽”my other event”事件,進行處置

載入SocketIO套件Library

建立SocketIO連線

聽取事件,進行反應動作

Enhance First App

● 修改為Server持續push資料至Client● Push的資料內容加上時間參數

其他SocketIO啟動方式 - HTTP Server

var app = require('http').createServer(handler) , io = require('socket.io').listen(app)app.listen(8088);

function handler (req, res) { res.writeHead(200); res.end(....);}

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

其他SocketIO啟動方式 - Express

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) {…..

其他範例

http://socket.io/#how-to-use

進階的SocketIO範例 - SocketIO Talkfunction handler (req, res) { //implement of reading chat.html}io.sockets.on('connection', function (socket) { socket.on('addme',function(username) { //implement of emit event user add }); socket.on('sendchat', function(data) { //implement of emit event of chat }); socket.on('disconnect', function() { //implement of emit evnet of disconnect });});

進階的SocketIO範例 - SocketIO Talk<script> var socket = io.connect('/'); socket.on('connect', function() { //implement of connect event }); socket.on('chat',function(username, data) { //implement of chat event receive }); $(document).ready(function(){ $('#sendtext').click(function(){

//implement of submit chat }); });</script>

Today’s Code

[email protected]:peihsinsu/class-nodejs-socketio.git

Q&A...