First WebSocket client code
This commit is contained in:
parent
51238d47a1
commit
4211560f20
|
|
@ -1,8 +1,44 @@
|
|||
// Constants and variables
|
||||
var wsUri = "ws://localhost:8765";
|
||||
|
||||
|
||||
// Initialization
|
||||
function init() {
|
||||
console.log("Init...");
|
||||
openWebSocket();
|
||||
}
|
||||
|
||||
// Open WebSocket
|
||||
function openWebSocket() {
|
||||
websocket = new WebSocket(wsUri);
|
||||
websocket.onopen = function(evt) { onOpen(evt) };
|
||||
websocket.onclose = function(evt) { onClose(evt) };
|
||||
websocket.onmessage = function(evt) { onMessage(evt) };
|
||||
websocket.onerror = function(evt) { onError(evt) };
|
||||
}
|
||||
|
||||
// WebSocket event handlers
|
||||
function onOpen(evt) {
|
||||
console.log('Connected to ' + wsUri + '.');
|
||||
|
||||
text = "Meow";
|
||||
console.log('Sending "' + text + '".');
|
||||
websocket.send(text);
|
||||
}
|
||||
|
||||
function onClose(evt) {
|
||||
console.log("Connection closed.");
|
||||
}
|
||||
|
||||
function onMessage(evt) {
|
||||
console.log('Received: "' + evt.data + '".');
|
||||
}
|
||||
|
||||
function onError(evt) {
|
||||
console.error('Error: "' + evt.data + '".');
|
||||
}
|
||||
|
||||
|
||||
// Run script after page is loaded
|
||||
$(function() {
|
||||
init();
|
||||
|
|
|
|||
Loading…
Reference in New Issue