Skip to content

Instantly share code, notes, and snippets.

@patrikbego
Last active June 6, 2023 10:41
Show Gist options
  • Save patrikbego/acd1eb069195c78d9db7edb8a0eb6a3c to your computer and use it in GitHub Desktop.
Save patrikbego/acd1eb069195c78d9db7edb8a0eb6a3c to your computer and use it in GitHub Desktop.
Simple Javascript WebSocket Client
// This is a Websocket client (can be run in browser console)
// ref client https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
// The standalone server can be found here https://gist.github.com/patrikbego/447c40f8eaee709d7a6a2d2cadbfd046
const URL = 'ws://localhost:8000';
let websocket;
function updateStatus(status) {
if (status === 'connected') {
console.log('All good');
}
}
function onOpen() {
updateStatus('connected');
}
function onMessage(evnt) {
if (typeof evnt.data === 'string') {
console.log(evnt.data.substring(0, evnt.data.indexOf(':')));
console.log(evnt.data.substring(evnt.data.indexOf(':') + 1));
}
}
function onError(evnt) {
alert(`ERROR: ${evnt.data}`);
}
function connect() {
websocket = new WebSocket(URL);
websocket.onopen = function (evnt) { onOpen(evnt); };
websocket.onmessage = function (evnt) { onMessage(evnt); };
websocket.onerror = function (evnt) { onError(evnt); };
}
function sendMessage() {
websocket.send('Hello');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment