state = "authenticating"; function authenticate(event) { $("#alert").hide(); websocket.send(JSON.stringify({name: $("#username").val() })); } function send(event) { websocket.send("\"" + $("#uinput").val() + "\"\n"); $("#uinput").val(""); } $(function(){ $("#auth").hide(); $("#alert").hide(); $("#stream").hide(); $("#uinputs").hide(); $("#submit-username").click(authenticate); $("#submit-uinput").click(send); setupWS(); }); function setupWS() { a = document.createElement("a"); a.href = document.URL; url = "ws://" + a.hostname + ":8000/ws/"; websocket = new WebSocket(url); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onclose = function(evt) { onClose(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; } function onOpen(e) { console.log("websocket opened"); $("#auth").show(); } function onClose(e) { console.error("websocket disconnected"); $("#alert").show().text("client disconnect; please reload page"); $("#stream, #auth").hide(); } function onMessage(e) { var payload = JSON.parse(e.data); if (state === "authenticating") { if (!payload.success) { console.error(payload); $("#alert").show().text(payload.error); return; } $("#auth").hide(); $("#stream").show(); $("#uinputs").show(); $(':input').keydown(function (e){ if(e.keyCode == 13){ send(); } }) state = "chatting"; } else if (state === "chatting") { var msg = $("#msg").clone(); msg.text(payload); $("#chatter").prepend(msg.show()); var s = $("#chatter").children().size(); if (s > 20) { var s = $("#chatter").children().last().remove(); } } } function onError(e) { console.error("websocket connection failure: " + JSON.stringify(e)); } function negociate() { var payload = {name: $("#username").val()}; websocket.send(JSON.stringify(payload)); }