Created
July 3, 2018 12:28
-
-
Save OliverLeitner/5affa3f5cd2cf8e801bcab10238048eb to your computer and use it in GitHub Desktop.
websockets with ws and less module dependencies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"author": "Jalal.Hejazi", | |
"info": "Response header info", | |
"Content-Type":"text/json", | |
"X-Powered-By":"nodejs", | |
"Access-Control-Allow-Origin":"*", | |
"next":"REST The WEB" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> | |
const socket = new WebSocket('ws://localhost:2222', 'ws'); | |
writeMessage = ((msg) => { | |
let msgArea = document.getElementById("msgArea"); | |
if (typeof msg == "object") { | |
msgArea.innerHTML = msg.data; | |
} else { | |
msgArea.innerHTML = msg; | |
} | |
}); | |
puller = (() => { | |
socket.onmessage = ((event) => { | |
console.log(event); | |
writeMessage(event); | |
}); | |
}); | |
puller(); | |
pushMe = (() => { | |
socket.send('hello world!'); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//websocket server lib | |
const WebSocket = require('ws'); | |
//fetch functionality for node | |
const fetch = require('node-fetch'); | |
//default web socket server | |
const wss = new WebSocket.Server({ port: 2222 }); | |
//grab some test data for in' | |
popMe = ((socket) => { | |
return fetch('http://localhost:1234/data.json') | |
.then((resp) => { | |
if (resp.status === 200) { | |
return resp.json(); | |
} | |
}).then((json) => { | |
socket.send(json.author); | |
}); | |
}); | |
//grab some test data for pushin' | |
getNews = ((socket) => { | |
fetch('http://localhost:1234/data.json') | |
.then((resp) => { | |
if (resp.status === 200) { | |
return resp.json(); | |
} | |
}).then((json) => { | |
socket.send(json.next); | |
}); | |
}); | |
wss.on('connection', ((ws) => { | |
ws.on('message', ((message) => { | |
console.log('received: %s', message); | |
popMe(ws); | |
})); | |
getNews(ws); | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment