socket.io模塊是一個基於Node.js的項目,其作用主要是將WebSocket協議應用到所有的瀏覽器。該模塊主要應用於實時的長連接多請求項目中,例如在線聯網游戲、實時聊天、實時股票查看、二維碼掃描登錄等。——Node.js開發實戰詳解
安裝和配置的方法和一般的NPM模塊安裝配置一致:
# npm install soctet.io
應該是因為我的本地服務器是win7操作系統,所以在安裝的時候會有一堆錯誤提示,但是貌似不影響使用socket.io模塊,沒有太在意這個。不知道在linux上是不是也這樣,等有時間會去我的服務器上試一下。
這里推薦一個官方的socket.io模塊的實例教程,實現了一個在線聊天的功能,對學習這個模塊有不小的幫助。
接下來介紹一下socket.io中常用的接口。
1.io.sockets.on('connection',function(socket){}):這個接口是socketAPI中的socket.on接口,它和下面的socket.on接口有一點區別。每當有用戶連接時,它都會執行一次回調函數。這里有三點需要注意,io.sockets.on中是sockets,發送的事件名為connection,還有回調函數需要傳入一個參數socket。
2.soctet.on('event',function(){}):這個的作用是接收到事件后執行回調函數。第一個參數是事件名,第二個參數是要執行的回調函數。
3.socket.emit('event',{test:'hello world'},function(){}):這個接口是發送一個事件。第一個參數是事件名,第二個參數是發送的數據內容,第三個參數是需要執行的回調函數。
4.socket.broadcast.emit('event',function(){}):就和他的接口名一樣會像廣播發給其他連接網站的用戶。但是有一點比較費解,他不會發給來源,打個比方:A用戶連接網站時會給服務器發送一個連接事件,服務器收到后用這個接口廣播發給所有連接着的用戶一個通知事件,然后用戶B、用戶C……都能收到這個通知事件,而用戶A不會收到。
5.socket.send('hello'):第一個參數是發送的數據,和emit類似,都是用來發送數據,但是如果用send發送,無法指定事件名,接收時會用message事件來接收,而emit可以自己定義事件名來接收數據。因此通常都是用emit,不建議使用send。
6.socket.get/set('foo', bar, function () {}):第一個參數是數據名,第二個參數是發送的數據,第三個是回調函數,set用來進行保存數據的操作,get用來取出已保存的數據。
最后貼上我自己測試用的代碼:
server:
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ console.log('a user connected'); socket.broadcast.emit('hi'); socket.on('chat message', function(msg){ io.emit('chat message', msg); }); socket.on('disconnect', function(){ console.log('user disconnected'); }); }); io.emit('some event', { for: 'everyone' }); http.listen(3000, function(){ console.log('listening on *:3000'); });
client:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
<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));
});
socket.on('hi', function(msg){
console.log('hi');
});
</script>
</html>
