The WSHubsAPI
package/module allows an intuitive communication between back-end (Python) and front-end (Python, JS, JAVA or Android) applications through the webSocket protocol.
pip install WSHubsAPI
Bellow you can find an example of how easy is to create a chat room with this library.
In this example we will use the WS4Py library and the ws4py clientHandler for the webssocket connections.
from WSHubsAPI.ConnectionHandlers.WS4Py import ClientHandler
from wsgiref.simple_server import make_server
from ws4py.server.wsgirefserver import WSGIServer, WebSocketWSGIRequestHandler
from WSHubsAPI.Hub import Hub
from ws4py.server.wsgiutils import WebSocketWSGIApplication
if __name__ == '__main__':
class ChatHub(Hub):
def sendToAll(self, name, message):
#onMessage function has to be defined in the client side
self.allClients.onMessage(name,message)
return "Sent to %d clients"%len(self.allClients)
#Hub.constructPythonFile("_static") #only if you will use a python client
Hub.constructJSFile("_static") #only if you will use a js client
server = make_server('127.0.0.1', 8888, server_class=WSGIServer,
handler_class=WebSocketWSGIRequestHandler,
app=WebSocketWSGIApplication(handler_cls=ClientHandler))
server.initialize_websockets_manager()
server.serve_forever()
works like:
<!DOCTYPE html>
<html>
<head>
<title>tornado WebSocket example</title>
<!--File auto-generated by the server.
Path needs to match with Hub.constructJSFile path parameter-->
<script type="text/javascript" src="_static/WSHubsApi.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"></script>
</head>
<body>
<div class="container">
<h1>tornado WebSocket example with WSHubsAPI</h1>
<hr>
WebSocket status : <span id="status">Waiting connection</span><br>
Name: <input type="text" id="name" value="Kevin"/><br>
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<script>
hubsApi = new HubsAPI('ws://127.0.0.1:8888/')
function sendToAll(){
var name = $('#name').val(),
message = $('#message').val()
$('#discussion').append('<li><strong> Me'
+ '</strong>: ' + message + '</li>');
hubsApi.ChatHub.server.sendToAll(name, message).done(function (numOfMessagesSent){
console.log("message sent to " + numOfMessagesSent + " client(s)");
},function (message){
console.log("message not sent" +message);
});
$('#message').val('').focus();
}
hubsApi.wsClient.onopen = function(){
$('#status').text("Connected")
//function to be called from server
hubsApi.ChatHub.client.onMessage = function(from, message){
$('#discussion').append('<li><strong>' + from
+ '</strong>: ' + message + '</li>');
}
//sending message
$('#sendmessage').click(sendToAll);
$('#message').keypress(function(e){
if (e.which == 13)
sendToAll()
});
};
hubsApi.wsClient.onclose = function(ev){
$('#status').text("Closed")
};
hubsApi.wsClient.onerror = function(ev){
alert(ev)
};
</script>
</body>
</html>
change raw_input for input for python 3.*
# File auto-generated by the server
# Path needs to match with Hub.constructPythonFile paths parameter
from _static.WSHubsApi import HubsAPI
import sys
if __name__ == '__main__':
hubsApi = HubsAPI('ws://127.0.0.1:8888')
hubsApi.connect()
def printMessage(senderName, message):
print(u"From {0}: {1}".format(senderName, message))
hubsApi.ChatHub.client.onMessage = printMessage
name = raw_input("enter your name:")
print("Hello %s. You have entered in the chat room, write and press enter to send message" % name)
while True:
message = raw_input("")
hubsApi.ChatHub.server.sendToAll(name, message).done(lambda m: sys.stdout.write(m),
lambda m: sys.stdout.write("!!!!!message not sent!!!!!\n"))
Not a beta version yet, working on it! ;)
To view and log any message from and to the server, user the logging package
import logging
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
The latest version of WSHubsAPI
is available on PyPI and GitHub.
For bug reports please create an issue on GitHub.
If you have questions, suggestions, etc. feel free to send me
an e-mail at jorge.girazabal@gmail.com
_.
This software is licensed under the MIT license
_.
© 2015 Jorge Garcia Irazabal.