本来后端已经写好轮询的接口,但是持续的http请求及其浪费资源,所以还是了解了一下websocket。由于做支付的需要了解了一下websocket。可查看socket.io 官方demo——一个简易的聊天程序。
需要的工具Node,使用的web框架express,自行安装。直接上代码吧~!基本把demo的代码copy了一遍。
服务端Node.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/',function(req,res){
// res.send('<h1>Hello word </h1>');
res.sendFile(__dirname + '/index.html')
});
http.listen(3000,function(){
console.log('request succeed!')
})
io.on('connection',function(socket){
socket.on('chat message',function(msg){
socket.emit('return message', msg);
})
});
html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button type="submit">Send</button>
</form>
<script>
$(function () {
var socket = io();
$('button').click(function(){
console.log('发送');
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('return message',function(msg){
console.log('接收');
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
运行
node index
效果