Node.js Socket.io
1) 安裝Node.js
下載 node.js binary code (v 6.3.1) 並複製到/usr/local 下- wget https://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.xz
- tar Jxvf node-v6.3.1-linux-x64.tar.xz
- cd node-v6.3.1-linux-x64/
- sudo cp * -r /usr/local/
- node -v ==> 會輸出 v6.3.1
2) 安裝 Express
- npm install -g express-generator
2) 從GitHub程式下載, 用這個範例快速學習Socket.io
git clone https://github.com/guille/chat-example.gitcd chat-example;
sudo npm install --save
# 執行node 程式
node index.js
出現==> listening on *:3000
開兩個瀏覽器連到 http://xxx.xxx.xxx.xxx:3000
######## index.html ########
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
######## index.js ########
// express 處理route ,url path 作為主要的程式app
// 軟體層次 : io(http(express))
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){ // http;//xxx.xxx.xxx.xxx: 3000 ,傳回/index.html
res.sendFile(__dirname + '/index.html');
});
// 再收到'connection' event後會獲得socket, 可以作socket.on('event', handler()) 進行讀socket
// 送出是透過 io.emit(''event', message);
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function(){ //斷線時即browser關閉
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
######## index.js ########
// express 處理route ,url path 作為主要的程式app
// 軟體層次 : io(http(express))
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){ // http;//xxx.xxx.xxx.xxx: 3000 ,傳回/index.html
res.sendFile(__dirname + '/index.html');
});
// 再收到'connection' event後會獲得socket, 可以作socket.on('event', handler()) 進行讀socket
// 送出是透過 io.emit(''event', message);
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function(){ //斷線時即browser關閉
console.log('user disconnected');
});
});
http.listen(3000, function(){ //listen on port 3000
console.log('listening on *:3000');
});
});
http.listen(3000, function(){ //listen on port 3000
console.log('listening on *:3000');
});
參考資源:
沒有留言 :
張貼留言