首先:
需要在服务器端安装node.js,然后安装express,socket.io这两个模块,并配置好相关的环境变量等。
其次:
服务端代码如下:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3031); io.on('connection', function (socket) {
console.log('websocket has connected');
socket.emit('message', {
static: 0
});
socket.on('num', function (data) {
console.log(data.num);
io.sockets.emit('last', {
result: data.num
});
});
});
前端代码1如下:
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="socket.io.js"></script>
<script src="jquery.min.js"></script>
</head> <body>
<div class="result">1</div>
<div class="addOne">加1</div>
<script>
var socket = io.connect('http://localhost:3031');
socket.on('message', function (data) {
console.log(data);
});
var result = 0;
$('.addOne').click(function () {
result += 1;
$('.result').html(result);
socket.emit('num', {
num: result
})
});
</script> </body> </html>
前端代码2如下:
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="socket.io.js"></script>
<script src="jquery.min.js"></script>
</head> <body>
<div class="result">加1</div>
<script>
var socket = io.connect('http://localhost:3031');
socket.on('message', function (data) {
console.log(data);
});
socket.on('last', function (data) {
console.log(data);
$('.result').html(data.result);
});
</script>
</body> </html>
小结:通过以上代码,我们可以实现类似于聊天的功能,或者长连接功能。
注意,及时通讯的功能,不同于普通的请求,相应。而是一直保持通讯中,前端发送,后端接收,后端然后再发送,前端再相应,这样保持着一直的连接。