Skip to content

JorgeGarciaIrazabal/WSHubsAPI

Repository files navigation

WSHubsAPI

The package helps you handle complex communications in a server/clients architecture.
Forget to handle web-socket messages with huge switch cases or maintain url strings for your API-REST. Just call server functions from the client and call client function from the server like it is the same program.
But not only that! with this package you will be able to communicate client applications with different languages or communication protocols at the same time!

Available coding languages:

  • Server side:
    • only python
  • Client side:
    • python
    • javascript
    • java/android (on going)
    • c++/arduino (on going)
    • micro-python (planned)

Communication protocols

This package is mainly a message handler so it doesn't matter which communication protocol you use as long as you create a Wrapper to handle it. However, we provide handlers to start coding right away :)

  • Web-Sockets for tornado and ws4py
  • Http requests for Django and tornado frameworks (of course we lose server to client communication)
  • Socket

Of course, any contribution will be more that appreciated ;)

Installation

The next command will install wshubsapi with the minimum dependencies required.

pip install wshubsapi

To run all the examples and tests, install following packages:

pip install flexmock
pip install tornado
pip install ws4py
pip install xmlrunner
pip install coverage
pip install requests
pip install django

Examples of usage

Bellow you can find an examples of how easy is to create a chat room with this library.

Server side

In this example we will use the tornado framework and the tornado clientHandler for the web-socket connections. For this example, remember to install tornado package.

pip install tornado
from wshubsapi.hubs_inspector import HubsInspector
from wshubsapi.connection_handlers.tornado_handler import ConnectionHandler
from tornado import web, ioloop
from wshubsapi.hub import Hub
import logging

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)

    class ForumHub(Hub):
        def publish_message(self, user_name, message):
            # get all connected clients to call client functions directly from here
            all_clients = self.clients.get_all_clients()
            # messagePosted function has to be defined in the client side
            all_clients.messagePosted(user_name, message)
            return "Sent to %d user(s)" % len(all_clients)

    # inspect Hubs in project to be included in the api environment
    HubsInspector.inspect_implemented_hubs()
    # create api modules to be used by the clients
    HubsInspector.construct_python_file()  # python api module will be created in current working dir
    HubsInspector.construct_js_file()  # javascript api library will be created in current working dir

    # initialize server
    app = web.Application([(r'/(.*)', ConnectionHandler)])
    app.listen(8888)
    logging.debug("server is listening in port: {}".format(8888))
    ioloop.IOLoop.instance().start()

Client side JS client

works like:

<html>
<head>
    <title>HubsAPI example</title>
    <!--File auto-generated by the server.
    Path needs to match with Hub.construct_js_file path parameter-->
    <script type="text/javascript" src="hubsApi.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"></script>
</head>
<body>
<div>
    <h1>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="post" value="Post"/>
    <ul id="discussion"/>
</div>
<script>
    var hubsApi = new HubsAPI();
    function postMessage() {
        var name = $('#name').val(),
            message = $('#message').val();

        hubsApi.ForumHub.server.publishMessage(name, message)
            .then(function (serverReplay) {
                console.log("Server replayed:  " + serverReplay);
            });

        $('#message').val('').focus();
    }

    hubsApi.connect('ws://127.0.0.1:8888/').then(function () {
        $('#status').text("Connected");
    });
    hubsApi.ForumHub.client.messagePublished = function (from, message) {
        $('#discussion').append('<li><strong>' + from
            + '</strong>: ' + message + '</li>');
    };

    $('#post').click(postMessage);
</script>
</body>
</html>

Client side Python client

change raw_input for input for python 3.*

# file created by the server
from hubs_api import HubsAPI


def message_posted(user_name, msg):
    print("{} posted:\n{}".format(user_name, msg))


if __name__ == '__main__':
    ws = HubsAPI('ws://127.0.0.1:8888/')
    ws.connect()
    name = raw_input("What is your name: ")
    # defining client function to be called from server
    ws.ForumHub.client.messagePosted = message_posted

    print("Hello %s!" % name)
    while True:
        message = raw_input("Write whatever you want to post it in the forum: ")
        # ws.ForumHub.server.publish_message is automaticly by the server in HugsAPI module
        server_replay = ws.ForumHub.server.publish_message(name, message).result(timeout=3)
        print("Server replay: {}".format(server_replay))

Client side JAVA/Android client

Not a beta version yet, working on it! ;)

Client side C++/Arduino client

Not a beta version yet, working on it! ;)

Other examples

find other examples in folder .../wshubsapi/examples. Where you can find http request or old socket communication together with more functionality.

Enabling logging

To view and log any message from and to the server, user the logging package

import logging
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)

Contact

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 [email protected]_.

License

This software is licensed under the MIT license_.

© 2015 Jorge García Irazábal.

About

Protocol to communicate backend (python) and frontend (android and web application) like signalR

Resources

Stars

Watchers

Forks

Packages

No packages published