基于node的websocket示例

时间:2023-07-02 13:30:50

websocket:用语服务器端主动向客户端推送消息

本例基于koa框架编写用例:服务器端需要安装相关模块 koa koa-socket co等

服务器端脚本:(需要安装相关模块 koa koa-socket co等)
//服务端
const Koa = require( 'koa' )
const IO = require( 'koa-socket' )
const co = require( 'co' ) const app = new Koa()
const io = new IO({
namespace:"mysocket",
ioOptions:{
path:'/restapi/websocketstock'
}
})
const TIME = 3000; //定时向客户端发送消息
let TimerId = null; io.use( co.wrap( function *( ctx, next ) {
let start = new Date()
yield next()
console.log( `response time: ${ new Date() - start }ms` )
})) // io.use( ... ); io.on("connection",function(){ //连接成功
console.log("successfully connect to websocket");
}); //定时向客户端推送消息
function sendToClient(){
TimerId = setInterval(function(){
io.broadcast('stockchallenge', {"userNum":parseInt(Math.random()*100)});
},TIME);
} //监控客户端发来的消息源
io.on('messageClient', ( ctx, data ) => {
console.log("来自客户端的消息");
console.log(data);
}) io.attach( app );
sendToClient(); app.listen( 3004 );
console.log("app is listening at 3004");

  

客户端脚本:在客户端,websocket需要浏览器支持才能使用,不过有许多js脚本对浏览器做了兼容性封装,本例以socket.io为例,

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>users count: <span id="count"></span></div>
<script src="js/socket.io.js"></script>
<script> var socket = io.connect( "http://机器名:3004/mysocket",{
path:"/restapi/websocketstock"
}); socket.on("connect",function(){
console.log("连接成功");
}); var sessionId;
//监控服务器端的消息 stockchallenge
socket.on("stockchallenge", function (data) {
console.log("来自服务器端的消息",data);
document.getElementById("count").innerHTML = data.userNum; }); </script>
</body>
</html>