Skip to content

Instantly share code, notes, and snippets.

@crongro
Created December 11, 2015 05:10
Show Gist options
  • Save crongro/824cbc41770b1b7939de to your computer and use it in GitHub Desktop.
Save crongro/824cbc41770b1b7939de to your computer and use it in GitHub Desktop.
websocket client ex
<html>
<head>
<style>
#log{
width : 600px;
height : 400px;
border : 1px solid red;
margin-bottom : 10px;
}
</style>
</head>
<body>
<div id="main">
<div id="log">
<p>dd</p>
<p>dd</p>
</div>
<div>
<button id="send">send message</button>
<button id="disconnect">good bye~</button>
</div>
</div>
</body>
</html>
<script>
if(!window.NEXT) { window.NEXT = {}; }
if(!console.log) { console.log = {}; }
function log(message) { console.log(message); }
function $(id) { return document.getElementById(id); }
dataInfo = {
websocketURL : "ws://echo.websocket.org/"
}
NEXT.ws = {
onOpenFn : function (event) {
log("onopen : " + event.data);
oWebsocket.send("hi websocket server!");
},
onCloseFn : function(event) {
log("onClose : " + event);
},
onErrorFn : function(event) {
log("onError : " + event);
},
onMessageFn : function(event) {
log("onMessage from server : -> " +event.data);
utility.insertMessage(event.data);
},
run : function() {
console.log("this->" + this);
oWebsocket = new WebSocket(dataInfo.websocketURL);
oWebsocket.onopen = this.onOpenFn;
oWebsocket.onclose = this.onCloseFn;
oWebsocket.onerror = this.onErrorFn;
oWebsocket.onmessage = this.onMessageFn;
}
}
//utility function
var utility = (function(){
function insertMessage(message) {
var elLog = $("log");
log("ellog -> " + elLog);
elLog.insertAdjacentHTML('beforeend', "<p>"+message+"</p>");
}
return {insertMessage : insertMessage};
})();
window.addEventListener("load" , NEXT.ws.run.bind(NEXT.ws) , false);
$('send').addEventListener("click", NEXT.ws.onOpenFn.bind(NEXT.ws), false);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment