aboutsummaryrefslogtreecommitdiffstats
path: root/templates/index.html
blob: 8de9627c47944021faf6a0d76dc29b8652788f4c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<!DOCTYPE html>
<meta charset="utf-8" />
<title>snekboxweb</title>
<script language="javascript" type="text/javascript">


let _ready = false
let snekbox_id
var output;

snekbox_id = sessionStorage.getItem("snekbox_id");
console.log(snekbox_id)
if (snekbox_id == null) {
    snekbox_id = generate_id()
    sessionStorage.setItem("snekbox_id", snekbox_id)
    console.log(snekbox_id)
}

function init(){
    output = document.getElementById("output");
    websocketHandler();
}

function websocketHandler(){
    var here = window.location.host;
    var wsUri = `ws://${here}/ws/`+snekbox_id;
    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) };
}

function onOpen(evt){
    _ready = true
    console.log("CONNECTED");
}

function onClose(evt){
    _ready = false
    console.log("DISCONNECTED");
}

function onMessage(evt){
    writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
}

function exit(){
    websocket.close();
}

function onError(evt){
    _ready = false
    writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}

function sendMessage(msg){
    waitForSocketConnection(function(){
        websocket.send(msg);
    });
    console.log("sent message "+msg)
}

function waitForSocketConnection(callback){
    setTimeout(
        function () {
            if (_ready === true) {
                if(callback != null){
                    callback();}
                return;
            }
            else {
                waitForSocketConnection(callback);}

        }, 500); // milliseconds
}

function writeToScreen(message){
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
}

function sendFromInput(){
    var msg = document.getElementById("field1").value;
    sendMessage(msg)
}

function generate_id(){
    return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}

window.addEventListener("load", init, false);

</script>

<textarea rows="4" cols="50" type="text" id="field1">
def sum(a,b):
    return a+b
print( sum(1,2) )
</textarea>
<br>
<button onclick="sendFromInput()">Send</button>
<button onclick="exit()">disconnect from websocket</button>
<div id="output"></div>