How to integrate SockJS with another web framework - websocket

As an alternative to Socket.io, there is SockJS (https://github.com/sockjs/sockjs-client), which seems to be better maintained and more stable than Socket.io.
This question is about the conceptual understanding the architecture of using SockJS with a web framework, say, for building a chat application
My current understanding is that you need the SockJS-client and a SocketJS server (in my case, I intend to use SockJS-Tornado (https://github.com/MrJoes/sockjs-tornado)) to be able to make websockets-style communication.
But how does SockJS (SockJS-client + SockJS-Tornado) tie together with a web framework that does the rest of the work (e.g. serving the page, writing/reading to/from db, etc). For instance, how would SockJS-Tornado component communicates with the web server of the framework? In particular, any direction of doing this with web2py (a python web framework) is highly appreciated.

You're right, for SockJS you need a sockjs-capable server and a in-browser javascript client library.
There are generally two integration patterns, let's say you want to use sockjs-tornado:
You may have all your site served from Tornado. With that, hook sockjs-tornado to some path, for example 'http://mysite.com/sockjs'. In this scenario both your website and sockjs will be served from mysite.com domain.
You may keep your site in whatever language/framework it's written and add sockjs-serveras another compontent, under a different domain, like. 'http://sockjs.mysite.com/sockjs'.
Additionally, you may use any variation of this - for example: have two servers internally but expose them as one domain by using a smart loadblancer (like haproxy).

If you're using web2py as a framework you could look a comet_messaging.py in gluon/contrib. It provides a function (comet_send) for getting messages from web2py app out to your websocket clients. It is based on tornado (w/o SockJS support) but the DistributeHandler can subclass a SockJS connection to provide fallback transport support. In this approach your clients send messages via typical GET or POST HTTP requests which are handled by web2py controllers (or other framework) and receive messages from the web2py controllers calling comet_messaging.comet_send() which sends a post request to the tornado instance which then blasts it out to its list of listeners.
The modified lines in comet_messaging look like (Notice open becomes on_open):
class DistributeHandler(sockjs.tornado.SockJSConnection):
def on_open(self, r):
group,token,name = [None, None, None]
self.group = group or 'default'
self.token = token or 'none'
self.name = name or 'anonymous'
and
urls=[
(r'/', PostHandler),
(r'/token', TokenHandler),
(r'/realtime', DistributeHandler)]
Notice I had to remove the regex group in the DistributeHandler URLSpec because sockJS-tornado was choking on it. Still trying to figure out how get parameters from the path to the on_open handler.

This provides a full answer on how to integrate SockJS into Django: https://stackoverflow.com/a/10950702/675065
Basically you need:
Tornado + SockJS-Tornado
Redis + Brukva
I use this configuration in my own project and it works pretty well.
Or: You try the autobahn way: http://autobahn.ws/ (i didn't try it out yet)

Related

Translate in aiohttp

There is some app with aiohttp used just for REST.
Front written in React/Redux.
The most part of application is translated on Frontend side.
But there are also message generated by aiohttp on server side (for example messages about form validation).
What's the best practise to handle these messages?
Make all translation on Frontend side?
There is https://github.com/jie/aiohttp_babel
Did not use it yet though

Cannot make ajax call between servers that differ only in port in HTML5/jQuery/Chrome stack

The parts
I am developing against two Pylons servers and testing locally. One server is on port 5000 and is the called server. The other is on port 7000. The latter creates a cookie that specifies the same domain as used by the former server. Essentially, the first server uses credentials provided by the second server to impersonate the user.
The first server expects to find an auth token (a cookie, really) in its response.environ at run time. When I authenticate on the server on port 7000 and browser to a service on port 5000, the latter server uses the cookie created by the former and the app works.
The fly in the ointment is that the first server creates an HTML5 app that uses an ajax call to the second server, and I cannot get the cookie to be included in the ajax call. I believe that Chrome (the browser we are using/requiring for HTML5 support reasons) refuses to send the cookie for cross domain reasons: going from foo.net:7000 to foo.net:5000 is considered cross domain.
Oh, and the ajax call is through jQuery.
The question
Is there any way to make an ajax call from an HTML5 app created on a port in the same domain to a server in the same domain but a different port?
What I've tried or discard out of hand
I do not believe I can use dynamic script tag insertion because I am making the call from javascript and the HTML is generated on the client at runtime from other javascript. At least, I don't think that is a desirable solution.
I don't believe Access-Control-Allow-* is applicable because I am going from client to server, not the other way.
I've seen this on jQuery and ports in ajax calls. I've seen this, too.
I know about the same-origin policy.
And this does not work.
Agree with Michael that the simplest solution is JSONP. But even in JSONP you need to configure your server such that it supports JSONP. Many Servers deny this to keep their data secure and sound. JSONP expect your server to send data in the format that can be evaluated as the valid JSON. But its not the case in every JSONP Request and response. So, just watch out for that.
The absolutely simplest solution to this is to use JSON/P. I wish there were an easier, softer way to accomplish this, but I certainly haven't found one.

How to use websocket to strengthen ajax?

HTML5 will be next super star.
So~~~How to using new idea to implement AJAX on the WebSocket in HTML5 spec?
thx....
I think you misunderstand ajax and websockets.
All internet programs operate by using a special kind of connection known as a socket (sockets can also be used for other things, but thats not important right now). For example, when you access a webpage in Chrome, Chrome creates a socket and uses that to connect to the webserver (there are other steps, but thats the simple explanation).
Ajax is a method for updating content on a page without reloading that page (or going to a new page), this is useful for dynamic content. Ajax works through the XMLHttpRequest object in the DOM Api. When you make an Ajax request, you're asking the web browser to initiate a new connection on your behalf (the web browser may then create a new socket as it sees fit).
Websockets is an alternative api which allows you more control over the socket the web browser creates. In essence its an alternative technology which accomplishes a similar purpose. Ajax sends only a single HTTP request (usually post or get), and receives the appropriate response, thus the advantage of websockets are 2 fold:
Websockets allows for non HTTP transfers (for example, streaming VoIP).
Websockets allow for bi-direction transfers, (ie. servers making follow up requests to client).
This is not to say Ajax isn't still useful, but that Websockets allow you to do things you can't with Ajax.

How to call Java web service (JAX-WS) from AJAX?

I am developing java web services (JAX-WS) to insert data into mysql DB and retrieve it. This web service has two methods i.e. fetchFromDB and insertIntoDB. Services seems to be running fine when I test them using netbeans IDE.
Address: /CalculatorWSService
WSDL: /CalculatorWSService?wsdl
but when I try to access it using AJAX's xmlHttpRequest object by providing url http://localhost:8080/CalculatorApp/CalculatorWSService. It is not able to access it. I have developed C# web services and It has been so easy to access them with a url but java web services don't seem to follow that.
My question is
What url to use to access the web service operations in AJAX? (Do I need to use '?wsdl' in the url?
Is there a javascript ajax library to easily access JAX-WS web services?
Apache Axis web services are a better choice over JAX-WS?
Please help me, Thanks, Jay
I was having the same problem of yours, couldn't invoke a Jax-ws web service from Javascript, but i've found a way to do this.
The Url to use can be your same (EndPointAddress) "http://localhost:8080/CalculatorApp/CalculatorWSService"
but when you create the XMLHttpRequest object from javascript you have to:
* Use the POST method to open the URL , i tried with GET but it didn't work for me.
* Set the SOAPAction Request Header to the one in your wsdl, even if its empty "".
* Be very careful with the request body to send, the soap Envelope must be correct.
hope this can help you!.
Bye.
Paul Manjarres.
From the client's perspective, I wasn't expecting significant differences between Axis and JAX-WS. Everything the client needs should be in the WSDL.
One thing that sometimes happens is that the URL used when developing a WebService references the develpoment host and port (and maybe even the ContextRoot) When deployed to a particular server any of those could be changed. Ideally a new WSDL could be created with new "binding" information.
My first step would be to point a browser directly at the Web Service you want to invoke. In my environments that returns a nice "Hi this is a Web Service" kind of message. If you get 401 not found errors then you just need to study exactly how the web service was deployed. Was a different port or context root specified?

Are there any MVC web frameworks that support multiple request types?

In every MVC framework I've tried (Rails, Merb, Waves, Spring, and Struts), the idea of a Request (and Response) is tied to the HTTP notion of a Request. That is, even if there is an AbstractRequest that is a superclass of Request, the AbstractRequest has things like headers, request method (GET, POST, etc.), and all of the other things tied to HTTP.
I'd like to support a request-response cycle over SMS, Twitter, email, or any other medium for which I can make an adapter. Is there a framework that does this particularly well?
The only other option I've thought of is creating, for example, a Twitter poller that runs in a separate thread and translates messages into local HTTP requests, then sends the responses back out.
If there were a good framework for multiple request media, what would routing look like? In Rails, the HTTP routing looks something like:
map.connect 'some/path/with/:parameter_1/:paramter_2', :controller => 'foo', :action => 'bar'
How would a Twitter or SMS route look? Regular expressions to match keywords and parameters?
I haven't seen one. The issue is that the request is also tied to the host, and the response is tied to the request.
So if you get a request in via email, and a controller says to render view "aboutus", you'd need the MVC framework to know how to :
get the request in the first place - the MVC framework would almost need to be a host (IIS doesn't get notified on new emails, so how does your email polling code get fired?)
allow flexible route matching - matching by path/url wouldn't work for all, so request-specific controller routing would be needed
use the aboutus email view rather than the SMS or HTTP view named "aboutus"
send the response out via email, to the correct recipient
A web MVC framework isn't going to cut it - you'll need a MVC "host" that can handle activation through web, sms, email, whatever.
The Java Servlet specification was designed for Servlets to be protocol neutral, and to be extended in a protocol-specific way - HttpServlet being a protocol-specific Servlet extension. I always imagined that Sun, or other third poarty framework providers, would come up with other protocol-specific extensions like FtpServlet or MailServlet, or in this case SmsServlet and TwitterServlet.
Instead what has happened is that people either completely bypassed the Servlet framework, or have built their protocols on top of HTTP.
Of course, if you want to implement a protocol-specific extension for your required protocols, you would have to develop the whole stack - request object, response object, a mechanism of identifying sessions (for example using the MSISDN in an SMS instead of cookies), a templating and rendering framework (equivalent of JSP) - and then build an MVC framework on top of it.
You seem to be working mostly with Java and/or Ruby, so forgive me that this answer is based on Perl :-).
I'm very fond of the Catalyst MVC Framework (http://www.catalystframework.org/). It delegates the actual mapping of requests (in the general, generic sense) to code via engines. Granted, all the engine classes are currently based on HTTP, but I have toyed with the idea of trying to write an engine class that wasn't based on HTTP (or was perhaps tied to something like Twitter, but was separated from the HTTP interactions that Twitter uses). At the very least, I'm convinced it can be done, even if I haven't gotten around to trying it yet.
You could implement a REST-based Adapter over your website, which replaces the templates and redirects according to the input parameters.
All requestes coming in on api.yourhost.com will be handled by the REST based adapter.
This adapter would allow to call your website programmatically and have the result in a parseable format.
Practically this means: It replaces the Templates with an own Template Engine, on which this things happen:
instead of the assigned template, a generic xml/json template is called, which just outputs a xml that contains all template vars
then you can make your Twitter Poller, SMS Gateway or even call it from Javascript.

Resources