Skip to content

Commit

Permalink
Working example of Flask + gevent-socketio.
Browse files Browse the repository at this point in the history
  • Loading branch information
kcarnold committed Jun 29, 2012
0 parents commit 2a8110e
Show file tree
Hide file tree
Showing 5 changed files with 4,120 additions and 0 deletions.
5 changes: 5 additions & 0 deletions README
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
I couldn't find a minimal example of using [Flask](http://flask.pocoo.org/) (a small web framework) with [gevent-socketio](https://github.com/abourget/gevent-socketio) (a simple way to get websockets). So this is a straight-up port of the [chat example](https://github.com/abourget/gevent-socketio/blob/master/examples/chat.py) from gevent-socketio to Flask.

You'll need Flask and gevent-socketio installed. Then just run `python server.py`.


100 changes: 100 additions & 0 deletions chat.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<!DOCTYPE html>
<html>
<head>
<link href="stylesheets/style.css" rel="stylesheet">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js">
</script><script type="text/javascript" src="socket.io.js"></script>
<script>


WEB_SOCKET_SWF_LOCATION = "/WebSocketMain.swf";
WEB_SOCKET_DEBUG = true;

// socket.io specific code
var socket = io.connect();

socket.on('connect', function () {
$('#chat').addClass('connected');
});

socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});

socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$().append($('<b>').text(nicknames[i]));
}
});

socket.on('msg_to_room', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});

socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});

socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});

function message (from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}

// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
console.log('set-nickname');
socket.emit('nickname', $('#nick').val(), function (set) {
console.log('got',set);
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});

$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});

function clear () {
$('#message').val('').focus();
};
});
</script>
</head>
<body>
<div id="chat">
<div id="nickname">
<form id="set-nickname" class="wrap">
<p>Please type in your nickname and press enter.</p>
<input id="nick">
<p id="nickname-err">Nickname already in use</p>
</form>
</div>
<div id="connecting">
<div class="wrap">Connecting to socket.io server</div>
</div>
<div id="messages">
<div id="nicknames"></div>
<div id="lines"></div>
</div>
<form id="send-message">
<input id="message">
<button>Send</button>
</form>
</div>
</body>
</html>
48 changes: 48 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from gevent import monkey; monkey.patch_all()
from flask import Flask, request, send_file

from socketio import socketio_manage
from socketio.namespace import BaseNamespace
from socketio.mixins import RoomsMixin, BroadcastMixin

# The socket.io namespace
class ChatNamespace(BaseNamespace, RoomsMixin, BroadcastMixin):
def on_nickname(self, nickname):
self.environ.setdefault('nicknames', []).append(nickname)
self.socket.session['nickname'] = nickname
self.broadcast_event('announcement', '%s has connected' % nickname)
self.broadcast_event('nicknames', self.environ['nicknames'])
# Just have them join a default-named room
self.join('main_room')

def on_user_message(self, msg):
self.emit_to_room('main_room', 'msg_to_room', self.socket.session['nickname'], msg)

def recv_message(self, message):
print "PING!!!", message


# Flask routes
app = Flask(__name__)
@app.route('/')
def index():
return send_file('chat.html')

@app.route('/socket.io.js')
@app.route('/stylesheets/style.css')
@app.route('/WebSocketMain.swf')
def static_file():
return send_file(request.path[1:])

@app.route("/socket.io/<path:path>")
def run_socketio(path):
socketio_manage(request.environ, {'': ChatNamespace})


if __name__ == '__main__':
print 'Listening on http://localhost:8080'
app.debug = True
from socketio.server import SocketIOServer
SocketIOServer(('0.0.0.0', 8080), app,
namespace="socket.io", policy_server=False).serve_forever()

Loading

0 comments on commit 2a8110e

Please sign in to comment.