Skip to content

Commit

Permalink
[example] Clean up examples
Browse files Browse the repository at this point in the history
  • Loading branch information
lpinca committed Apr 25, 2019
1 parent 4a9a773 commit aca3858
Show file tree
Hide file tree
Showing 6 changed files with 103 additions and 54 deletions.
21 changes: 12 additions & 9 deletions examples/express-session-parse/index.js
Expand Up @@ -25,7 +25,7 @@ const sessionParser = session({
app.use(express.static('public'));
app.use(sessionParser);

app.post('/login', (req, res) => {
app.post('/login', function(req, res) {
//
// "Log in" user and set userId to session.
//
Expand All @@ -36,10 +36,11 @@ app.post('/login', (req, res) => {
res.send({ result: 'OK', message: 'Session updated' });
});

app.delete('/logout', (request, response) => {
app.delete('/logout', function(request, response) {
console.log('Destroying session');
request.session.destroy();
response.send({ result: 'OK', message: 'Session destroyed' });
request.session.destroy(function() {
response.send({ result: 'OK', message: 'Session destroyed' });
});
});

//
Expand All @@ -48,7 +49,7 @@ app.delete('/logout', (request, response) => {
const server = http.createServer(app);

const wss = new WebSocket.Server({
verifyClient: (info, done) => {
verifyClient: function(info, done) {
console.log('Parsing session from request...');
sessionParser(info.req, {}, () => {
console.log('Session is parsed!');
Expand All @@ -63,16 +64,18 @@ const wss = new WebSocket.Server({
server
});

wss.on('connection', (ws, req) => {
ws.on('message', (message) => {
wss.on('connection', function(ws, request) {
ws.on('message', function(message) {
//
// Here we can now use session parameters.
//
console.log(`WS message ${message} from user ${req.session.userId}`);
console.log(`WS message ${message} from user ${request.session.userId}`);
});
});

//
// Start the server.
//
server.listen(8080, () => console.log('Listening on http://localhost:8080'));
server.listen(8080, function() {
console.log('Listening on http://localhost:8080');
});
6 changes: 3 additions & 3 deletions examples/express-session-parse/package.json
Expand Up @@ -4,8 +4,8 @@
"version": "0.0.0",
"repository": "websockets/ws",
"dependencies": {
"express": "~4.16.3",
"express-session": "~1.15.6",
"uuid": "~3.3.2"
"express": "^4.16.4",
"express-session": "^1.16.1",
"uuid": "^3.3.2"
}
}
37 changes: 23 additions & 14 deletions examples/express-session-parse/public/app.js
@@ -1,46 +1,55 @@
/* global fetch, WebSocket, location */
(() => {
(function() {
const messages = document.querySelector('#messages');
const wsButton = document.querySelector('#wsButton');
const logout = document.querySelector('#logout');
const login = document.querySelector('#login');

const showMessage = (message) => {
function showMessage(message) {
messages.textContent += `\n${message}`;
messages.scrollTop = messages.scrollHeight;
};
}

const handleResponse = (response) => {
function handleResponse(response) {
return response.ok
? response.json().then((data) => JSON.stringify(data, null, 2))
: Promise.reject(new Error('Unexpected response'));
};
}

login.onclick = () => {
login.onclick = function() {
fetch('/login', { method: 'POST', credentials: 'same-origin' })
.then(handleResponse)
.then(showMessage)
.catch((err) => showMessage(err.message));
.catch(function(err) {
showMessage(err.message);
});
};

logout.onclick = () => {
logout.onclick = function() {
fetch('/logout', { method: 'DELETE', credentials: 'same-origin' })
.then(handleResponse)
.then(showMessage)
.catch((err) => showMessage(err.message));
.catch(function(err) {
showMessage(err.message);
});
};

let ws;

wsButton.onclick = () => {
wsButton.onclick = function() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}

ws = new WebSocket(`ws://${location.host}`);
ws.onerror = () => showMessage('WebSocket error');
ws.onopen = () => showMessage('WebSocket connection established');
ws.onclose = () => showMessage('WebSocket connection closed');
ws.onerror = function() {
showMessage('WebSocket error');
};
ws.onopen = function() {
showMessage('WebSocket connection established');
};
ws.onclose = function() {
showMessage('WebSocket connection closed');
};
};
})();
19 changes: 13 additions & 6 deletions examples/server-stats/server.js → examples/server-stats/index.js
@@ -1,26 +1,33 @@
const WebSocketServer = require('../../').Server;
'use strict';

const express = require('express');
const path = require('path');
const app = express();
const server = require('http').createServer();
const { createServer } = require('http');

const WebSocket = require('../../');

const app = express();
app.use(express.static(path.join(__dirname, '/public')));

const wss = new WebSocketServer({ server: server });
const server = createServer(app);
const wss = new WebSocket.Server({ server });

wss.on('connection', function(ws) {
const id = setInterval(function() {
ws.send(JSON.stringify(process.memoryUsage()), function() {
/* ignore errors */
//
// Ignore errors.
//
});
}, 100);
console.log('started client interval');

ws.on('close', function() {
console.log('stopping client interval');
clearInterval(id);
});
});

server.on('request', app);
server.listen(8080, function() {
console.log('Listening on http://localhost:8080');
});
2 changes: 1 addition & 1 deletion examples/server-stats/package.json
Expand Up @@ -4,6 +4,6 @@
"version": "0.0.0",
"repository": "websockets/ws",
"dependencies": {
"express": "~4.16.3"
"express": "^4.16.4"
}
}
72 changes: 51 additions & 21 deletions examples/server-stats/public/index.html
@@ -1,33 +1,63 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Server stats</title>
<style>
body {
font-family: Tahoma, Geneva, sans-serif;
table, td {
border: 1px solid #333;
}

div {
display: inline;
thead {
background-color: #333;
color: #fff;
}
</style>
</head>
<body>
<h1>Server stats</h1>
<table>
<thead>
<tr>
<th colspan="2">Memory usage</th>
</tr>
</thead>
<tbody>
<tr>
<td>RSS</td>
<td id="rss"></td>
</tr>
<tr>
<td>Heap total</td>
<td id="heapTotal"></td>
</tr>
<tr>
<td>Heap used</td>
<td id="heapUsed"></td>
</tr>
<tr>
<td>External</td>
<td id="external"></td>
</tr>
</tbody>
</table>
<script>
function updateStats(memuse) {
document.getElementById('rss').innerHTML = memuse.rss;
document.getElementById('heapTotal').innerHTML = memuse.heapTotal;
document.getElementById('heapUsed').innerHTML = memuse.heapUsed;
}
(function() {
const rss = document.getElementById('rss');
const heapTotal = document.getElementById('heapTotal');
const heapUsed = document.getElementById('heapUsed');
const external = document.getElementById('external');
const ws = new WebSocket(`ws://${location.host}`);

var host = window.document.location.host.replace(/:.*/, '');
var ws = new WebSocket('ws://' + host + ':8080');
ws.onmessage = function (event) {
updateStats(JSON.parse(event.data));
};
ws.onmessage = function(event) {
const data = JSON.parse(event.data);

rss.textContent = data.rss;
heapTotal.textContent = data.heapTotal;
heapUsed.textContent = data.heapUsed;
external.textContent = data.external;
};
})();
</script>
</head>
<body>
<strong>Server Stats</strong><br>
RSS: <div id='rss'></div><br>
Heap total: <div id='heapTotal'></div><br>
Heap used: <div id='heapUsed'></div><br>
</body>
</html>

0 comments on commit aca3858

Please sign in to comment.