So recently one of my project allow me to have experience on gevent-socketio. While the code is open source, it can be complicated. Thus the example I show here, while not serious hopefully will make things easier to see.
You will need these dependency,
Before we can start to create a view for socket-io you will need to define the namespace to be used
from socketio.namespace import BaseNamespace
if attack['type'] == 'fireball':
for i in range(10):
The gevent-socketio library uses Namespace as the view logic, all the logics will be in a namespace, along with namespace, there is also Mixins that is built on top of namespace that provide extra functionality, gevent-socketio provide BroadcastMixin and RoomMixin, which is useful.
line 3: We create our namespace by subclassing Namespace Class
line 4: This is method defined by us. We prefix on_ to an event that we want to process. In this case it is the ping event. The event will be send from socketio client. The parameter attack, that is essentially the payload that we will be receiving, and we don’t need to do any conversion from json to dict, as the library handle it for us.
line 7 and 9: Self.emit will emit an event to the socketio client, again the dict, is the payload that will be sent, no converstion to json necessary.
Now we can finally define a view
from flask import Flask
from flask import request
from socketio import socketio_manage
app = Flask(__name__)
This is the view for socketio. app is just your standard flask app.
line 7: is the route necessary for the socketio client to connect
line 9: this is the same across socketio app, the difference here is the namespace ‘/pingpong’ and the namespace PingPong, that you will need to define yourself.
Now to serve this guy
from socketio.server import SocketIOServer
# app will be somewhere around here
if __name__ == "__main__":
line 6: this will be the line that serve the app. It will serve all the views include the non-socketio one.
var socket = io.connect('/pingpong');
$('#result').append(data.sound + '<br/>');
attack = $(this).data('attack');
line 2: This is how you define a socket io.connect(‘/namespace’)
Hopefully this will make things slightly clearer. Btw the example on github.