初探WebSocket(一)

其实也不是初探啦,之前一直用的socket.io,感觉对内部实现不了解。

参考:1.ws文档,https://github.com/websockets/ws/blob/master/doc/ws.md

================================== demo ===============================

server.js

const http = require('http');
const fs = require('fs');
const WebSocke = require('ws');

//打开文件
function router(req, res) {
	if (req.url === '/') {
		fs.readFile('./www/index.html', 'utf8', function (err, data) {
			res.end(!err ? data : '<h1>index.html is not defined</h1>');
		});
	} else {
		res.end('successful');
	}
}

const app = http.createServer(router), app_port = 1234;
app.listen(app_port, () => {
	console.log(`server start at http://localhost:${app_port}`);
});
//最新文章ws
const newest_crticle_ws = new WebSocke.Server({server: app, path: '/newest_crticle',});
let newest_crticle_connect_set = new Set;
Object.defineProperty(newest_crticle_connect_set, 'notify', {
	value() {
		this.forEach(ws => {
			ws.send(JSON.stringify({
				event: 'newest_crticle_connect_count',
				data: newest_crticle_connect_set.size,
			}));
			ws.send(JSON.stringify({
				event: '222',
				data: newest_crticle_connect_set.size,
			}));
		});
	},
})
newest_crticle_ws.on('connection', function (ws) {
	newest_crticle_connect_set.add(ws).notify();
	ws.on('close', function () {
		newest_crticle_connect_set.delete(ws);
		newest_crticle_connect_set.notify();
	});
});

client.js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>当前网站连接数:
    <span id="site-connect-count">

    </span>
</h1>
<script>
	const ws = new WebSocket('ws://localhost:1234/newest_crticle');
	const event_hanlder_map = {
		newest_crticle_connect_count: function () {
			const input = document.getElementById('site-connect-count');
			return function (data) {
				input.innerText = data;
			};
		}(),
	};
	ws.addEventListener('message', function (event) {
		try {
			const msg = JSON.parse(event.data);
			event_hanlder_map[msg.event](msg.data);
		} catch (e) {
		}
	});
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_39571197/article/details/82811201