Skip to content

Instantly share code, notes, and snippets.

@zed

zed/andreymal.py Secret

Last active August 29, 2015 14:26
Show Gist options
  • Save zed/56f9bd5d33fff51f6820 to your computer and use it in GitHub Desktop.
Save zed/56f9bd5d33fff51f6820 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""From
http://ru.stackoverflow.com/q/433554/23044
Run:
$ python3 -mpip install websockets
$ python3 andreymal.py
$ python3 -mhttp.server --bind localhost
$ python -mwebbrowser http://localhost:8000/sendkeys.html
Press Ctrl+C in the shell with `andreymal.py` script.
See whether it produces an error.
"""
import asyncio
import logging
import websockets # $ pip install websockets
log = logging.getLogger(__name__).info
@asyncio.coroutine
def echo_upper(websocket, path):
log('client started')
while True:
message = yield from websocket.recv()
if message is None:
break
if not websocket.open:
break
yield from websocket.send(message.upper())
log('client finished')
logging.basicConfig(level=logging.INFO, datefmt="%F %T",
format="%(asctime)s %(message)s")
loop = asyncio.get_event_loop()
start_server = websockets.serve(echo_upper, '127.0.0.1', 8888, loop=loop)
server = loop.run_until_complete(start_server)
log('Listen')
try:
loop.run_forever()
except KeyboardInterrupt:
pass
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
log('Finished')
<!doctype html>
<title>Send keys using websocket and echo the response</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<script src="sendkeys.js"></script>
<input type=text id=entry value="type something">
<div id=output>Here you should see the typed text in UPPER case</div>
// send keys to websocket and echo the response
$(document).ready(function() {
// create websocket
if (! ("WebSocket" in window)) WebSocket = MozWebSocket; // firefox
var socket = new WebSocket("ws://localhost:8888");
// open the socket
socket.onopen = function(event) {
socket.send('connected');
// show server response
socket.onmessage = function(e) {
$("#output").text(e.data);
}
// for each typed key send #entry's text to server
$("#entry").keyup(function (e) {
socket.send($("#entry").attr("value"));
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment