Skip to content

Instantly share code, notes, and snippets.

@otaks
Created May 1, 2016 23:11
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 otaks/1bc0529c1d6c54fada2548b939dd6e6b to your computer and use it in GitHub Desktop.
Save otaks/1bc0529c1d6c54fada2548b939dd6e6b to your computer and use it in GitHub Desktop.
chat_sample
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(function() {
var data = {};
ws = new WebSocket("ws://192.168.33.10:8080/chat");
ws.onopen = function() {
ws.send('hi');
};
ws.onmessage = function(e) {
$("#holder").append($('<p>'+e.data+'</p>'));
};
$('#sender').append($('<button/>').text('send').click(function(){
ws.send($('#message').val());
}));
});
</script>
</head>
<body>
<div id="sender">
<input type="text" id="message" value="text" />
</div>
<h3>Messages</h3>
<div id="holder"></div>
</body>
</html>
import os
import random
from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi, sleep
ws_list = set()
def chat_handle(environ, start_response):
global cnt
ws = environ['wsgi.websocket']
ws_list.add(ws)
print 'enter!', len(ws_list)
while 1:
#msg = ws.wait()
msg = ws.receive()
if msg is None:
break
remove = set()
for s in ws_list:
try:
s.send(msg)
except Exception:
remove.add(s)
for s in remove:
ws_list.remove(s)
print 'exit!', len(ws_list)
def myapp(environ, start_response):
path = environ["PATH_INFO"]
print "path=" + path
#if path == "/":
if path == "/" or path == "/favicon.ico":
start_response("200 OK", [("Content-Type", "text/html")])
return open('./chat_sample.html').read()
elif path == "/chat":
return chat_handle(environ, start_response)
raise Exception('Not found.')
server = pywsgi.WSGIServer(('0.0.0.0', 8080), myapp, handler_class=WebSocketHandler)
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment