我写的websocket推送例子,每隔5秒服务器向客户端浏览器发送消息(node.js和浏览器)
node.js服务端
先要安装ws模块的支持
npm install ws
服务端(server.js)
var gws; var WebSocketServer = require('ws').Server, wss = new WebSocketServer({ port: 9000 }); wss.on('connection', function (ws) { gws = ws; console.log('client connected'); ws.on('message', function (message) { console.log(message); setInterval(show,5000);//每隔5秒 服务端向浏览器 推送消息 }); }); function show() { gws.send(1122); }
shell> node server.js
浏览器客户端
<script> if (window.WebSocket) { console.log("支持"); }else { console.log("不支持"); } var ws = new WebSocket('ws://localhost:9000'); ws.onopen = function() { console.log("open"); ws.send("hello"); }; ws.onmessage = function(evt) { console.log(evt.data) }; ws.onclose = function(evt) { console.log("WebSocketClosed!"); }; ws.onerror = function(evt) { console.log("WebSocketError!"); }; </script>