Migrating Ajax web application to web socket - java

I think I'm just missing a little detail that is preventing me from seeing the whole picture.
I have a web application which use ajax request every x time to update client with new information or tasks.
I also have a long running process on the server which is a java computation engine. I would like this engine to send update to the client.
I am wondering how to migrate my web app to using websocket. Probably phpwebsocket or similar. Can my server 'decide' to send information to a specific client? It seems possible looking at the php-websocket.
Can my java backend long process use the websocket server to send notification to a specific client. How? well I can say that my java app could use a class that could send over websocket instead of http.
But how the websocket server knows to which client to send the 'info'. I am puzzle by all this. Any document that explain this in more details? It seems that the websocket could create an instance of my web application.
Thanks

Your server, which will have an arbitrary number of active client sockets, decides which ones to write to (possibly in response to input from the user).
phpwebsocket (which is still very rough around the edges) has a User class with $id, $socket (this is the underlying TCP socket), and $handshake fields. You could extend that class with additional metadata about the User (e.g. a computation identifier). Or you could use an array mapping from computation id to User.
Perhaps when Java computation n finishes, you can look up the socket associated with that computation, and write to its socket.

Related

How to wait in a continuous loop in servlet?

I am developing a servlet based application. One situation is that a client requests some data from a database which is sent back in the form of html. The client will modify this data and then sent it back to the server. Now the twist starts. There is not a single client. So multiple clients can request the same data. So what I am doing is that when the first client makes a request, this request is stored somewhere so that when the next user makes the same request he is denied the data.
Now suppose the first user gets the data and 2nd is denied. Now while the first user is on the html page which allows him to modify the data. I want to send continuous javascript async post requests at a fixed interval to inform the server that the client is active.
At the server side I need a thread or something which can keep waiting in a loop for the javascript async requests and if the request is not received within the fixed time then the thread removes the saved request so that future requests to the data will be accepted.
I have searched the entire day and looked at things like async servlets, ServletContext listener and scheduledExecutorservice. I dont want to use scheduledExecutorService as it is invoked at app startUp which I dont want to do since this specific situation is a minor part of the code and to handle it I dont want something running all the time. I need some background service which keeps running even after the server has returned requested data.
Servlets won't fulfill your requirements, therefore you should use WebSockets.
As per my understanding, you are trying to push data from the server, therefore you need to a push architecture instead of pull architecture (Servlets are based upon pull architecture).
Java has native support of WebSockets
You can find several tutorials on how to use WebSockets in a Java Web Application.
Here is a link to a basic WebSockets Tutorial.
Hope this helps

Restlet streaming data

I have this task that I'm undertaking where I would be reading data from a device and make it available over a web service. The data is read 4 times a second. I want the web clients to be have an open HTTP connection and get the device readings as a stream using chunked transfer as long as the client keeps the connection open.
As a proof of concept, I want to start with a service that constantly generates a random number, 4 times a second, wraps it in json and stream that to clients. I'm trying to model it loosely based on twitter streaming api.
I'm using restlet 2.1.2 to create that webservice but I'm not sure which Representation I should be using to achieve this. I tried searching for this but didn't find anything useful. Could someone point me in the right direction as to what I should be using and maybe some examples, perhaps.
Thanks
To achieve what you are trying to do, I'd use the WriterRepresentation (but see my answer to your other question), but I'm quite sure that you are going in the wrong architectural direction.
Indeed the following image from the documentation you linked
shows how even the Twitter streaming api is not intended to be connected by users, but by background processes that download messages in a store accessible by the HTTP. Users poll only the HTTP server, that reads the messages from the store and sends the back to the clients.
As a disconnected protocol, HTTP enable massive scalability that would not be possible otherwise. If each client establishes a persistent TCP connection backed by a dedicated server thread, you will rapidly exaust server resources! Moreover any HTTP proxy between the User Agent and the server could cause unexpected behaviours.
Thus, if you are bound to the HTTP protocol, the User Agent should poll. You can reduce the network load with headers like Last-Modified/If-Modified-Since or Etag/If-None-Match.
However, if you can adopt a different protocol, I strongly suggest to try a service bus over a connected TCP protocol.

Can web server send data to desktop application without request?

I have several PC's on each of them I set small swing application that get data with JSON request to one web server. Can I receive the data from web server without to send request to the web server, with other words can the Web server send the data without the Java application to ask for this?
If you have enough server resources
you can consider usage of websockets.
Every PC can open a socket to the server.
When you open the socket you need to send to the server, the pc's unique ID.
Then you need to store this ID in some database or file that will contain all online pc's and sockets .
Then the Server will be aware which pc's are online and which socket to use to communicate with this pc. After this you can send whatever information you need to this PC depending on your application.
This can be implemented in several ways. One common way would be to open a connection and do blocking read in the client application. On receiving something it will look like push from the server. Then you process the push and do another blocking read.
Another option would be doing regular checks if there is something for you on the web server. You set the retry interval frequent enough so it will look like real time push from your app point of view.
If you use HTTP i think the smartest way is to drop the realtime requirement and use a thread that polls the server every 5 seconds. Keeping a HTTP Connection open all time is expensive as it blocks a request processor thread and limits the amount of clients you can have.
You might also consider moving to something like a registration mechanism if you really need near-realtime updates which is often not the case. You would have to open a Server on the clients and have the server push the updates after clients registered their Address with the server.

Push APIs like gmail, twitter and facebook does

I want to create an application using pushing mechanism. i.e. without user interaction we can push the messages to the client when some thing is happend in the server, similar to what gmail is done for their emails and facebook recent activity messages.
How can i implement this one using java.
Please help, Thanks in advance.
One technique to achive this is taking advantage of the long-polling method.
The client opens up a connection to the server, but instead of instantly returning the result, the server holds the connection for a period of time and delays his response.
If something happens, that causes the server response to trigger (new mail, new instant message ... ), the server finally answers to the client. Or, in the case the request runs in timeout, the server just passes an empty result.
In both cases, the client processes the response and instantly makes a new request, for the whole thing to start again.
In Java, the client side may do simple requests. The server side should be properly threaded, and the timout should not be set too long.
Also, please have a look at this SO thread:
Each webserver/appserver has a pool of threads, say 10 threads for processing web requests, if all those threads will go into 'sleep' no other web request will be serviced until one of those 'sleeps' exists.
What you need is called as Comet aka Reverse Ajax, there are multiple such implementation both paid and free.
Depending upon programming language you choose you can choose one of the following:
Tomcat Reverse Ajax.
Jetty Comet.
DWR
Streamhub (Paid but has a community edition)
APE. (Free not available for Windows)
Atmosphere (Used in Primefaces)
CometD by Dojo.
Or just use Pusher API. You use their REST service to publish events and Pusher then delivers these events to all clients via websockets. The API is easy to use and supports multiple channels.
Though a late answer , here is my take on how to do server push.You can use the socket-io framework coupled with nodejs.The socket-io client has to listen to events and the socket-io on the nodejs ( server ) can emit ( push ) the messages , the client ( socket-io in webpage ) picks it up and can do whatever it wants.There is a catch,you should know a little bit of javascript.The socket-io protocol is transport agnostic too !
Here are the links
An excellent writeup on using socket-io and nodejs
Socket-io
nodejs

Build a server for client/server side bidirectional communication feedback system in Java?

Scenario: User logs in on the client software which forms a persistent bidirectional connection with the serverside entity (server) which would process user specified tasks. When the serverside entity, while processing user's task, encounters an error or requires further user input, it will notify the client software, and wait until the client decides what to do. The client software will take the new user specifiefd inputs and send this to the serverside. The serverside continue where it last stopped with the new user specified inputs. This feedback cycle will continue until it's finished processing. The progressively updated user inputs will all be stored on the serverside and accessible and modifiable from the client software. So if a client deletes a specific input, that change will be immediately reflected on the serverside. On the serverside, an extra interface is probably required to route different user's clients to available hardware nodes (cloud) to support concurrent multi-user tasks running on the serverside.
On the client side, I suspect using sockets to connect to the server...
Now for the server, I am a little lost because there seems to be many different Java servers like Jetty & Netty. I am also practicing caution in order to not try and reinvent any wheels here.
Is building a server the right approach? or Build a webservice that will complete a specific task on demand?
I am also not just looking for a one size fits all solution (wishful thinking probably) but open to any insights on my current situation.
Netty will provide a lot of what it sounds like you need for this, without making you reinvent a socket server. That said, I would make certain that you actually need bidirectional, real-time communication between the client and server. If you can rework the problem such that the client-server communications do not need to be real-time, then things like RESTful webservices become a possibility, and (in my experience) are much less complicated and error prone.

Categories