Created
May 1, 2016 23:11
-
-
Save otaks/1bc0529c1d6c54fada2548b939dd6e6b to your computer and use it in GitHub Desktop.
chat_sample
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> | |
<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> |
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
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