Skip to content

Instantly share code, notes, and snippets.

@jbarros35
Created April 11, 2018 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbarros35/826ff8be8a4c0377b4a3c82371d6a80d to your computer and use it in GitHub Desktop.
Save jbarros35/826ff8be8a4c0377b4a3c82371d6a80d to your computer and use it in GitHub Desktop.
Open websocket on browser for a server running ws Node
// if user is running mozilla then use it's built-in WebSocket
window.WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('wss://localhost:443', 'echo-protocol');
connection.onopen = function () {
// connection is opened and ready to use
console.log('client opened socket');
$scope.send();
};
connection.onerror = function (error) {
// an error occurred when sending/receiving data
console.log('err: '+error);
};
connection.onmessage = function (message) {
// try to decode json (I assume that each message
// from server is json)
console.log('server response:'+message);
try {
var json = JSON.parse(message.data);
console.log(json);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ',
message.data);
return;
}
// handle incoming message
};
$scope.send = function() {
// Tell the server this is client 1 (swap for client 2 of course)
connection.send(JSON.stringify({
id: "client1"
}));
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment