Skip to content

Instantly share code, notes, and snippets.

@pradeepn
Last active August 29, 2015 14:14
Show Gist options
  • Save pradeepn/793f41fa056dc7361a39 to your computer and use it in GitHub Desktop.
Save pradeepn/793f41fa056dc7361a39 to your computer and use it in GitHub Desktop.
Websocket Client Implementation
//JS Client For Websockets Server
//For C# Use Fleck & NetSockets
//https://github.com/statianzo/Fleck
//https://netsockets.codeplex.com/Wikipage?ProjectName=netsockets
var ws;
$(document).ready(function () {
// test if the browser supports web sockets
if ("WebSocket" in window) {
debug("Browser supports web sockets!", 'success');
connect($('#host').val());//set ws/wss url
$('#console_send').removeAttr('disabled');
} else {
debug("Browser does not support web sockets", 'error');
};
// function to send data on the web socket
function ws_send(str) {
try {
ws.send(str);
} catch (err) {
debug(err, 'error');
}
}
// connect to the specified host
function connect(host) {
debug("Connecting to " + host + " ...");
try {
ws = new WebSocket(host); // create the web socket
} catch (err) {
debug(err, 'error');
}
$('#host_connect').attr('disabled', true); // disable the 'reconnect' button
ws.onopen = function () {
debug("connected... ", 'success'); // we are in! :D
};
ws.onmessage = function (evt) {
debug(evt.data, 'response'); // we got some data - show it omg!!
};
ws.onclose = function () {
debug("Socket closed!", 'error'); // the socket was closed (this could be an error or simply that there is no server)
$('#host_connect').attr('disabled', false); // re-enable the 'reconnect button
};
ws.onerror = function () {
debug("Socket closed!", 'error'); // the socket was closed (this could be an error or simply that there is no server)
$('#host_connect').attr('disabled', false); // re-enable the 'reconnect button
};
};
// function to display stuff, the second parameter is the class of the <p> (used for styling)
function debug(msg, type) {
$("#console").append('<p class="' + (type || '') + '">' + msg + '</p>');
if(window.console)
console.log(type+':'+msg);
};
// the user clicked to 'reconnect' button
$('#host_connect').click(function () {
debug("\n");
connect($('#host').val());
});
// the user clicked the send button
$('#console_send').click(function () {
ws_send($('#console_input').val());
});
$('#console_input').keyup(function (e) {
if(e.keyCode == 13) // enter is pressed
ws_send($('#console_input').val());
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment