Last active
September 14, 2017 19:23
-
-
Save sn1p3r46/1895293c632a0fb7c17a05532dc1aa61 to your computer and use it in GitHub Desktop.
Simple WebSocket Client-Server Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>WebSocket demo</title> | |
</head> | |
<body> | |
<script> | |
var messages = document.createElement('ul'); | |
function output(msg){ | |
var messages = document.getElementsByTagName('ul')[0]; | |
message = document.createElement('li'); | |
content = document.createTextNode(msg); | |
message.appendChild(content); | |
messages.appendChild(message); | |
} | |
function main(){ | |
var ws = new WebSocket("ws://127.0.0.1:5678/"); | |
ws.onclose = function(){ | |
console.log("attempting again...") | |
setTimeout(main, 3333); | |
} | |
ws.onmessage = function (event) { | |
output("1st handler msg: " + event.data); | |
ws.onmessage = function (myevent){ | |
output("2nd handler msg: " + myevent.data); | |
} | |
} | |
ws.onopen = function () { | |
ws.send("getCompetence") | |
} | |
} | |
document.body.appendChild(messages); | |
main(); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import asyncio | |
import random | |
import websockets | |
import json | |
async def time(websocket, path): | |
while True: | |
msg = await websocket.recv() | |
res = get_competence() | |
if msg == "getCompetence": | |
await websocket.send(res) | |
myJson = json.loads(res) | |
while True: | |
print("inside") | |
await asyncio.sleep(random.random() * 5) | |
await websocket.send(random_generator(myJson.keys())) | |
def get_competence(): | |
with open('competence1.json','r') as f: | |
return f.read() | |
def random_generator(keys): | |
reslen = random.randint(0,len(keys)-1) | |
res = [random_val(keys) for x in range(0,reslen)] | |
return json.dumps(res) | |
def random_val(keys): | |
res = {} | |
res["value"] = random.randint(1,5) | |
res["anomaly"] = random.randrange(100) < 10 | |
res["id"] = random.choice(list(keys)) | |
return res | |
if __name__ == "__main__": | |
start_server = websockets.serve(time, '127.0.0.1', 5678) | |
asyncio.get_event_loop().run_until_complete(start_server) | |
asyncio.get_event_loop().run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment