Skip to content

Instantly share code, notes, and snippets.

@OliverLeitner
Created July 3, 2018 08:56
Show Gist options
  • Save OliverLeitner/e6f7f2689584276e59f8c426fcad239b to your computer and use it in GitHub Desktop.
Save OliverLeitner/e6f7f2689584276e59f8c426fcad239b to your computer and use it in GitHub Desktop.
websockets playaround
{
"author": "Jalal.Hejazi",
"info": "Response header info",
"Content-Type":"text/json",
"X-Powered-By":"nodejs",
"Access-Control-Allow-Origin":"*",
"next":"REST The WEB"
}
<!doctype html>
<html>
<head>
<title>web sockets</title>
<meta charset="utf-8">
</head>
<body>
<button name="pusher" onClick="javascript:pushMe();">Push Me!</button>
<div id="msgArea">
</div>
<script src="/node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
const socket = io.connect('http://localhost:2222');
writeMessage = ((msg) => {
let msgArea = document.getElementById("msgArea");
if (typeof msg == "object") {
msgArea.innerHTML = msg;
} else {
msgArea.innerHTML = msg;
}
});
puller = (() => {
socket.on('news', ((data) => {
console.log(data);
writeMessage(data.next);
socket.emit('my other event', { my: 'data' });
}));
socket.on('replacer', ((data) => {
console.log(data);
writeMessage(data.author);
socket.emit('my other event', { my: 'data' });
}));
});
puller();
pushMe = (() => {
socket.emit('client_data', {message:'author'});
});
</script>
</body>
</html>
//fetch functionality for node
const fetch = require('node-fetch');
//initial page return
handler = ((req, res) => {
fs.readFile(__dirname + '/index.html',
((err, data) => {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
}));
});
//grab some test data for pushin'
getNews = (() => {
fetch('http://localhost:1234/data.json')
.then((resp) => {
if (resp.status === 200) {
return resp.json();
}
}).then((json) => {
pushMe(json);
});
});
//grab some test data for popin'
popMe = ((socket) => {
return fetch('http://localhost:1234/data.json')
.then((resp) => {
if (resp.status === 200) {
return resp.json();
}
}).then((json) => {
socket.emit('replacer', json);
});
});
//build the server
const app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs');
app.listen(2222);
//the pusher
pushMe = ((response) => {
io.sockets.on('connection', (socket => {
socket.emit('news', response);
socket.on('client_data', ((data) => {
console.log(data);
popMe(socket);
}));
}));
});
//initializing
getNews();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment