Created
February 16, 2015 14:28
-
-
Save omaraboumrad/9bff38260caa2e29b430 to your computer and use it in GitHub Desktop.
Experimenting with websocketd
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>Chat!</title> | |
<style> | |
</style> | |
</head> | |
<body> | |
<ul id="messages"></ul> | |
<input type="text" id="msg"/> | |
<button onclick="send()">Send</button> | |
<script> | |
var ws = new WebSocket('ws://127.0.0.1:8080/'); | |
ws.onopen = function() { | |
document.body.style.backgroundColor = '#cfc'; | |
}; | |
ws.onclose = function() { | |
document.body.style.backgroundColor = null; | |
}; | |
ws.onmessage = function(event) { | |
var ul = document.getElementById('messages') | |
var text = document.createTextNode(event.data); | |
var li = document.createElement('li'); | |
li.appendChild(text); | |
ul.appendChild(li); | |
}; | |
var send = function(){ | |
var msg = document.getElementById('msg').value; | |
ws.send(msg); | |
} | |
</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/env python | |
import sys | |
import imp | |
import select | |
from sys import stdout | |
# For some reason websocketd isn't picking up the site packages | |
sys.path.append('/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/') | |
import redis | |
server = redis.StrictRedis(host='localhost', | |
port=6379, | |
db=0) | |
hub = server.pubsub() | |
hub.subscribe('chat') | |
while True: | |
inputready, outputready, _ = select.select([sys.stdin], [sys.stdout], []) | |
if outputready: | |
m = hub.get_message() | |
if m and m['type'] == 'message': | |
print m['data'] | |
stdout.flush() | |
if inputready: | |
server.publish('chat', sys.stdin.readline().rstrip()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment