Skip to content

Instantly share code, notes, and snippets.

@omaraboumrad
Created February 16, 2015 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omaraboumrad/9bff38260caa2e29b430 to your computer and use it in GitHub Desktop.
Save omaraboumrad/9bff38260caa2e29b430 to your computer and use it in GitHub Desktop.
Experimenting with websocketd
<!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>
#! /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