情景交互:当客户端发送ping请求到服务器的时候,服务器响应pong。服务器发送ping请求到客户端的时候,客户端响应pong。
var http = require('http');
var fs = require('fs');
var server = http.createServer(function (req, res) {
fs.readFile('./index.html', function(error, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data, 'utf-8');
});
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.on('ping', function (data) {
console.log('Received PING. Sending PONG..');
socket.emit('pong', { text: 'PONG' });
});
socket.on('pong', function (data) {
console.log('Received PONG response. PONG!');
});
setInterval(function() {
console.log('Sending PING to client..');
socket.emit('ping', { text: 'PING' });
}, 10000);
});
setInterval():简单的按照所指定的时间间隔重复某些事情,10000毫秒为是10秒钟时间。
客户端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Socket.IO Example</title>
</head>
<body>
<h1>Socket.IO Example</h1>
<button id="ping">Send PING to server</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3000');
socket.on('ping', function (data) {
console.log('Received PING. Sending PONG..');
socket.emit('pong', { text: 'PONG' });
});
socket.on('pong', function (data) {
console.log('Received PONG response. PONG!');
});
$('#ping').click(function() {
console.log('Sending PING to server..')
socket.emit('ping', { text: 'PING' });
});
</script>
</body>
</html>
结果如下:
Sending PING to client..
debug - websocket writing 5:::{"name":"ping","args":[{"text":"PING"}]}
Received PONG response. PONG!
Sending PING to client..
debug - websocket writing 5:::{"name":"ping","args":[{"text":"PING"}]}
Received PONG response. PONG!
debug - emitting heartbeat for client 1290563434602710577
debug - websocket writing 2::
debug - set heartbeat timeout for client 1290563434602710577
debug - got heartbeat packet
debug - cleared heartbeat timeout for client 1290563434602710577
debug - set heartbeat interval for client 1290563434602710577
Sending PING to client..
debug - websocket writing 5:::{"name":"ping","args":[{"text":"PING"}]}
Received PONG response. PONG!
info - transport end
debug - set close timeout for client 1290563434602710577
debug - cleared close timeout for client 1290563434602710577
debug - cleared heartbeat interval for client 1290563434602710577
debug - discarding transport
Sending PING to client..
Sending PING to client..
Sending PING to client..
Sending PING to client..