iT邦幫忙

DAY 4
2

複製、貼上,接K屎 - 以nodeJS 為例系列 第 4

複製、貼上、玩node - socket.io 安裝

開發node 幾乎希望實做comet ,而socket.io 這個前後台整合模組,在實做comet 上十分推薦的一個外掛模組。
開發node之前,首先並重npm ,因為要使用到模組(module)的加持。畢竟在node 開發實際應用商品,很多坑洞都會導致整個node 程序crash,建議直接使用第三方模組開發,降低問題的發生率。

首先,在開發node 幾乎希望實做comet ,而socket.io 這個前後台整合模組,在實做comet 上十分推薦的一個外掛模組。

安裝socket.io
npm install socket.io [-g]
如果沒有看到紅字,表示安裝順利完成!

試用socket.io

node.JS 程式

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);
 });
});

Client 程式

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

上一篇
複製、貼上、玩node - npm 安裝
下一篇
複製、貼上、玩node - socket.io 解說
系列文
複製、貼上,接K屎 - 以nodeJS 為例6
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言