Created
April 11, 2018 13:01
-
-
Save jbarros35/826ff8be8a4c0377b4a3c82371d6a80d to your computer and use it in GitHub Desktop.
Open websocket on browser for a server running ws Node
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
// 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