Created
April 11, 2013 13:38
-
-
Save asjustas/5363442 to your computer and use it in GitHub Desktop.
websocket basic
This file contains hidden or 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
var connection = new WebSocket('ws://127.0.0.1:1337'); | |
connection.onopen = function () { | |
// first we want users to enter their names | |
input.removeAttr('disabled'); | |
status.text('Choose name:'); | |
}; | |
connection.onerror = function (error) { | |
// just in there were some problems with conenction... | |
content.html($('<p>', { text: 'Sorry, but there\'s some problem with your ' | |
+ 'connection or the server is down.</p>' } )); | |
}; | |
// most important part - incoming messages | |
connection.onmessage = function (message) { | |
// try to parse JSON message. Because we know that the server always returns | |
// JSON this should work without any problem but we should make sure that | |
// the massage is not chunked or otherwise damaged. | |
try { | |
var json = JSON.parse(message.data); | |
} catch (e) { | |
console.log('This doesn\'t look like a valid JSON: ', message.data); | |
return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment