1. Jeffrey Gelens
  2. gevent-socketio

Commits

sontek  committed c1c0a08 Merge

Merge remote-tracking branch 'sebastibe/master'

  • Participants
  • Parent commits f81a933, 322fe6e
  • Branches default

Comments (0)

Files changed (3)

File .gitignore

File contents unchanged.

File examples/chat.html

View file
-<!DOCTYPE html><html><head><link href="stylesheets/style.css" rel="stylesheet"><script src="http://code.jquery.com/jquery-1.6.1.min.js"></script><script src="socket.io.js"></script><script>// socket.io specific code
-var socket = io.connect("http://localhost:8080");
+<!DOCTYPE html>
+<html>
+  <head>
+    <link href="stylesheets/style.css" rel="stylesheet">
+    <script src="http://code.jquery.com/jquery-1.6.1.min.js">
+    </script><script src="socket.io.js"></script>
+    <script>    
+// socket.io specific code
+//var socket = io.connect('');
+var socket = io.connect();
 
 socket.on('connect', function () {
-  $('#chat').addClass('connected');
+    $('#chat').addClass('connected');
 });
 
 socket.on('announcement', function (msg) {
-	$('#lines').append($('<p>').append($('<em>').text(msg)));
+    $('#lines').append($('<p>').append($('<em>').text(msg)));
 });
 
 socket.on('nicknames', function (nicknames) {
-	$('#nicknames').empty().append($('<span>Online: </span>'));
-	for (var i in nicknames) {
-	  $('#nicknames').append($('<b>').text(nicknames[i]));
-	}
+    $('#nicknames').empty().append($('<span>Online: </span>'));
+    for (var i in nicknames) {
+	  $().append($('<b>').text(nicknames[i]));
+    }
 });
 
-socket.on('user message', message);
+socket.on('msg_to_room', message);
 socket.on('reconnect', function () {
-$('#lines').remove();
-	message('System', 'Reconnected to the server');
+    $('#lines').remove();
+    message('System', 'Reconnected to the server');
 });
 
 socket.on('reconnecting', function () {
-	message('System', 'Attempting to re-connect to the server');
+    message('System', 'Attempting to re-connect to the server');
 });
 
 socket.on('error', function (e) {
-	message('System', e ? e : 'A unknown error occurred');
+    message('System', e ? e : 'A unknown error occurred');
 });
 
 function message (from, msg) {
-	$('#lines').append($('<p>').append($('<b>').text(from), msg));
+    $('#lines').append($('<p>').append($('<b>').text(from), msg));
 }
 
 // dom manipulation
 $(function () {
-$('#set-nickname').submit(function (ev) {
-  socket.emit('nickname', $('#nick').val(), function (set) {
-    if (!set) {
-      clear();
-      return $('#chat').addClass('nickname-set');
-    }
-    $('#nickname-err').css('visibility', 'visible');
-  });
-  return false;
-});
+    $('#set-nickname').submit(function (ev) {
+        socket.emit('nickname', $('#nick').val(), function (set) {
+            if (!set) {
+                clear();
+                return $('#chat').addClass('nickname-set');
+            }
+            $('#nickname-err').css('visibility', 'visible');
+        });
+        return false;
+    });
 
-$('#send-message').submit(function () {
+    $('#send-message').submit(function () {
 	message('me', $('#message').val());
 	socket.emit('user message', $('#message').val());
 	socket.send("TESTING !@#")
 	clear();
 	$('#lines').get(0).scrollTop = 10000000;
 	return false;
+    });
+
+    function clear () {
+        $('#message').val('').focus();
+    };
 });
-
-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>
+    </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>

File examples/chat.py

View file
 from gevent import monkey; monkey.patch_all()
-from socketio import SocketIOServer
+from socketio import SocketIOServer, socketio_manage
+from socketio.namespace import BaseNamespace
+from socketio.mixins import RoomsMixin, BroadcastMixin
+
+
+class ChatNamespace(BaseNamespace, RoomsMixin, BroadcastMixin):
+    
+    def on_nickname(self, nickname):
+        self.environ['nicknames'].add(nikname)  
+        self.socket.session = nickname
+        self.broadcast_event('anouncement', '%s has connected' % nickname)
+        self.broadcast_event('nicknames', self.environ['nicknames'])
+
+    def on_join_room(self, room_name):
+        self.join(room_name)
+
+    def on_msg_to_room(self, room_name, msg):
+        self.emit_to_room('msg_to_room', room_name, msg)
 
 
 class Application(object):
     def __init__(self):
         self.buffer = []
-        self.cache = {
-            'nicknames': set()
-        }
 
     def __call__(self, environ, start_response):
         path = environ['PATH_INFO'].strip('/')
+        environ['nicknames'] = set()
 
         if not path:
             start_response('200 OK', [('Content-Type', 'text/html')])
             return [data]
 
         if path.startswith("socket.io"):
-            socketio = environ['socketio']
-
-            while True:
-                message = socketio.receive()
-
-                print message
-
-                if message and message['type'] == "event":
-                    self.handle_event(message, socketio)
+            socketio_manage(environ, {'': ChatNamespace})
         else:
             return not_found(start_response)
 
-    def handle_event(self, message, socketio):
-        if message['name'] == "nickname":
-            nickname = message['args'][0]
-            nickdict = {}
-            nickdict[nickname] = nickname
-            socketio.session.nickname = nickname
-
-            self.cache['nicknames'].add(nickname)
-
-            socketio.ack(message['id'], [0])
-            socketio.broadcast_event("announcement", "%s connected" % nickname)
-            socketio.broadcast_event("nicknames", list(self.cache['nicknames']), include_self=True)
-
-        elif message['name'] == "user message":
-            socketio.broadcast_event("user message", socketio.session.nickname, message['args'][0])
-
-
 def not_found(start_response):
     start_response('404 Not Found', [])
     return ['<h1>Not Found</h1>']