Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new example #208

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions examples/barebones_echo/README.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
This is a barebones "echo" example. It uses no css,
no flash (websocket), no magic javascript, and the
bare minimum in dependencies.

It's intended for one who is getting started, and
wants to understand the skeleton, and minimal lines
of code, to make socketio work.

There are only 2 short, main files: echo.py, and echo.js.
echo.py creates the SocketIOServer and provides a short
class, "Application", which is the basic web app, which
serves the front-page HTML (in-line, since it's short)
and calls socketio_manage() to run the BaseNamespace-
derived socket handler. SocketIOServer, BaseNamespace,
and socketio_manage() are the only real dependencies,
each with only 1 line of code, really, to make the whole
thing go.

The web page asks a user to type values for bar and baz.
When the "submit" button is pushed, an HTTP transaction
is _not_ performed; rather, the bit of code in echo.js
arrests the process and sends a socketio message, instead,
to foo(bar, baz), which is handled back in echo.py, with
on_foo(self, bar, baz), a function of the BaseNamespace-
derived class.

That's it! This example depends only on socketio (of
course) and jquery.
82 changes: 82 additions & 0 deletions examples/barebones_echo/echo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
from gevent import monkey; monkey.patch_all()

from socketio import socketio_manage
from socketio.server import SocketIOServer
from socketio.namespace import BaseNamespace

import htmltag as h

class EchoNamespace(BaseNamespace):

def recv_disconnect(self):
self.disconnect(silent=True) # kills all spawned jobs (none, in our case) and removes namespace from socket
print('Disconnected')

def on_foo(self, bar, baz):
print('Got on_foo(bar = "%s", baz = "%s")' % (bar, baz))
self.emit('echo', bar, baz) # echo it

class Application(object):

def __call__(self, environ, start_response):
path = environ['PATH_INFO'].strip('/')

if not path:
start_response('200 OK', [('Content-Type', 'text/html')])

return ['%s%s' % ('<!doctype html>', str(h.html(
h.head(h.meta(charset = 'UTF-8'), h.title('socketio echo test')),
h.script(src="/static/jquery-1.6.1.min.js", type="text/javascript"),
h.script(src="/static/socket.io.js", type="text/javascript"),
h.script(src="/static/echo.js", type="text/javascript"),
h.body(
h.p('''
This is an echo test for socketio.
When you enter values for 'bar' and 'baz'
and push 'emit', they'll be sent over a socket,
received by the server ('foo()'), and echoed back via
emitting 'echo' with 'rab' and 'zab'.
(no HTTP GET or POST is executed!)
'''),
h.hr(),
h.form(
'bar: ', h.input(type='text', id='bar'), ' ',
'baz: ', h.input(type='text', id='baz'),
h.button('Emit', type='submit'),
id = 'foo'),
h.hr(),
h.p(
# These will get values subbed in via javascript when rab and zab are echoed from server:
'rab: ', h.span(id = 'rab'), ' ',
'zab: ', h.span(id = 'zab'))
)
)))]

if path.startswith('static/'):
try:
data = open(path).read()
except Exception:
return not_found(start_response)

if path.endswith(".js"):
content_type = "text/javascript" # we don't have any other types in this simple example, so...
else:
return not_found(start_response)

start_response('200 OK', [('Content-Type', content_type)])
return [data]

if path.startswith("socket.io"):
socketio_manage(environ, {'/echo': EchoNamespace}, {})
else:
return not_found(start_response)


def not_found(start_response):
start_response('404 Not Found', [])
return ['<h1>Not Found</h1>']


if __name__ == '__main__':
print 'Listening on port 8080'
SocketIOServer(('0.0.0.0', 8080), Application(), resource="socket.io", policy_server=False).serve_forever()
30 changes: 30 additions & 0 deletions examples/barebones_echo/static/echo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
$(document).ready(function() { // this requires jquery!! ack, surely there's another way!!!!

var socket = io.connect('/echo');

$(window).bind("beforeunload", function() {
socket.disconnect();
});

socket.on("echo", function(rab, zab) {
$("#rab").text(rab);
$("#zab").text(zab);
});

socket.on("error", function(e) {
console.log(e ? e : "Unknown error occurred; 'error' received on socket with no value for 'e'");
});

// Execute whenever the form is submitted:
$("#foo").submit(function(e) {
e.preventDefault(); // don't allow the form to submit

var bar = $("#bar").val();
var baz = $("#baz").val();
socket.emit("foo", bar, baz);

$("#bar").val("");
$("#baz").val("");
});

})
18 changes: 18 additions & 0 deletions examples/barebones_echo/static/jquery-1.6.1.min.js

Large diffs are not rendered by default.

Loading