I'm implementing a long poll http connection using java servlet.
How can I know that the http client is still active at any instance? Currently, what I do is to write a byte to the output stream and flush data. If there's an IO exception then the client is dead.
But in ASP.NET there is a property, Response.IsClientConnected which can find out if the client is active without writing anything to the output stream.
I want to know how if it is possible to develop in java servlet. I do not want to keep writing data into the http response stream as it may cost network.
Thanks in advance.
It will be difficult to achieve that using Servlet APIs. Though the low level Socket APIs provide this functionality (Socket.isConnected() ), but same functionality is not available through any higher level APIs. Not sure if you any compulsions of using Servlet APIs or you can use low level socket APIs.
Maybe you've taken the wrong approach? HTTP protocol is developed to be used in a request-response style, it is not suited to be used for a long polling. In fact, there should be lowest possible delay before client gets a server response.
The case you've described looks like a job for a good old Socket.
Related
I am not looking specific answer, just an idea or a tip.
I have following problem:
Android application is a client for web service. It has a thread, which sends events (XML form with request ID) through http protocol and for every request server sends confirmation, that he understand message right with granted event ID - server is a synchronizer for few clients. I want use websocket protocol to send events through websocket too but it is a little bit tricky - instead of http, I don't expect to get response for every request. Moreover, incoming websocket messages is parsed in other thread. Primary mechanism it's a little bit overgrown and I don't want to write everything from scratch.
I want to make this asynchronous websocket mechanism to pretend to be synchronous.
There is my idea for now - after send event through websocket I will wait no more for e.g 5 seconds for response which will processed in other thread (it's came as XML) and regarding too request ID it will notify proper paused thread. I worry Condition.await() and condition.signal isn't the best idea, what do you think?
According to this problem, I've realized that I have problems with project this kind of mechanism. Do you have an idea, where can I find information about good pattern and tips which good to now to avoid bad approach? Thanks in advance!
The only difference between websocket and HTTP requests is the lack of HTTP headers when a message comes in. In websocket, you have a heartbeat that keeps the connection alive and allows full duplex communication, and then you have pure payloads. It's your job to find which message headers you will use to route the requests properly in your server/client.
So, that doesn't stop you from communicating in a request/response manner by simply writing to the output stream right after receiving. I suggest you take a look at the RFC
https://www.rfc-editor.org/rfc/rfc6455
If you're a little more visual, this slideshow can help:
http://www.slideshare.net/sergialmar/websockets-with-spring-4
Or if you want some more serious implementations as an example, take a look at spring's docs:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html
I've tried to create async-servlet for long-polling, using this tutorial on my Glassfish server, however it didn't work well, the POST requests were too long (timed out) and GET returned sometimes void response with "Error parsing XML file" firebug message. Can somebody please provide simple async-servlet for handling long-polling requests?
It is better you move away from the servlet based approach if you want to implement a long polling solution. Netty is very good choice for such applications. Just build a simple HTTP instance with child.keepAlive option in bootstrap kept to true (server doesnt close off the client connections). That way you don't need to deal with the servlet containers time out and connection handling intricacies. Netty is an asynchronous IO framework and should give you great performance matrix.
I currently have an TCP Java socket communication implementation in which I have a server that is listening to a port (let's say port 5478). Then I need an Android client to remotely connect to the Java server and send a SQL query, than will then be executed on the server side database and then I want to send a list of results back to the Android client (already implemented with a custom Java class named Result that implements Serializable). I do this by sending an ArrayList of Result to the Android client. The Java server is always listening to the port and supports multiple clients trough multiple Threads. How can I migrate this implementation to a more secure platform and what is the best way to do it? I don't need to respect HTTP protocol to afford this communication. Is Tomcat the best solution?
Thanks
I would use Servlet3.0 as part of tomcat.
Then from android you just have to send http requests to the server using a URL and the servlet can database them. You can also serialize the data as well if you need to.
I hope that answers your question.
~ Dan
//EDIT:
Once you have set up eclipse and tomcat, you can start writing servlets. First - you have to configure the server to use servlets for certain addresses, for example localhost:8080/myServlet - that means that anything you send to local host triggers the servlet. The code for your first servelet looks like this:
public class ExampServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Your doPost method is what gets called when you perform a http post request on the address the servlet is listening on. Then, all you have to do it put some code in to read the request to get the data out of the message body. Basically you read your request object that gets passed in, and you write to your response object to send the response back to the client. There are plenty of guides out there. I followed something like this to get started:
http://www.coreservlets.com/Apache-Tomcat-Tutorial/tomcat-7-with-eclipse.html
Hope that helps :)
~ Dan
Tomcat is an Servlet container + webserver. If you plan to move to tomcat then you are implicitly moving to http. And yes, if you want a secure communication .. you can create a soap based webservice(apache axis) and host it on https.
I'm not sure how mutch additional security tomcat is able to provide for your application. Two tings come to mind:
Enforcing authentication and some access rules. This is not too hart to implement and heavily depends on the rule quality. However it may help f you use it. It's often replaced by own imlpementations. However, to get securty you need encryption i.e. https. Or it's possible to steel the session and gain the rights bound to it.
Request to file mapping. This in fact somewhat more complicated. You shouldn't code this on your own. It's more complicated than it looks at first sight.
However, one of the biggest security wholes ever is directly executing code you got from somewhere. For example SQL statements. Ok it's secure as long as your databse rights are set perfectly...
Developing a securly encrypted protocol is not simple either.
However, the major win on switching to tomcat (or whatever) might be scaleability for free. And I think implementing servlets is much simpler than programming against sockets. And there are many great to tools fo working with http(s) though ven it might be more complicated than yours, it's pretty simple to deal with.
Unfortunately I can't answer our question. I don't know what's the best solution is. But I think there's at least some potential for wins.
I am doing some study on SOAP based web services with JAX-WS, and i am finding very complicated to understand the part regarding to the clients.
If some one could give me a hand explaining me some of the topics, i would appreciate it a lot. I am using a SOA book and also google, but i am getting really confused, so that's why i think here i can get a more accurate answer, focused on what i need.
So we can communicate with web services in a synchronous and an asynchronous way. Synchronous communication has the lack that both sides have to wait for each other until the processing ends.
Asynchronous clients allows us to communicate in an asynchronous manner using 2 programming models: 1- Callback and 2- Polling
Doubt 1: Can someone please explain me in a simple way what are the differences, pros and cons of the 2 models(Callback and Pooling)
When talking about asynchronous communication i also understand that there should be a way for the producer(Web Service), to find the consumer(client) once the processing is finished.That is why we have addressing.
Doubt 2: Could you briefly explain how addressing works? And also How is Addressing related to callback and polling techniques?
Just one more thing. The Dispatch API is also confusing me a lot. Because they keep talking about dynamic clients.
Doubt 3: How is the Dispatch API related to Asynchronous communication if they are talking all the time about dynamic clients?
Doubt 4: The 2 usages modes of the Dispatch API(MESSAGE and PAYLOAD), what are used for, and how are they related to the Asynchronous communication model of JAXWS?
Can someone please explain me in a simple way what are the differences, pros and cons of the 2 models(Callback and Pooling)
Callback: implementation is not straight forward.
- Advantage: this approach is more elegant/systematic comapred to the polling approach.
- Disadvantage: the client should have a mechanism so that the server can call it back using the callback.
Polling: implementation is straight forward.
- Advantage: becuase of it's simplicity of techique, it is universal, even an ajax enabled webpage can use this technique to check if the update to the request is available.
- Disadvantage: huge wasteage of bandwidth, also server client timing issues, like how long should the server hold the response incase polling request from client did not yet come.
2.Could you briefly explain how addressing works? And also How is Addressing related to callback and polling techniques?
Addressing makes it possible for the webservice to understand the information which was shared previously between messaging systems and transport providers only. Consider this usecase, Initially transport used would be HTTP for both sending request as well as response.And then you might want to change a part of this transport, say while sending the response back,only to SMTP protocol. Incase you were using ws addressing, the whole information related to transport and addressing would be part of the soap envolope itself which would make it possible for your webservice to dynamically change the transport to response sending.
Webservices addressing can also be used for callback, from the server to the client. The service informs port type of the callback required by it in the WSDL. the client implements this port type and then informs the service, of the callback endpoint, using the WS addressing.
In simple words, WS addressing adds extra tags to the soap envolope which includes information which would be present in the transport headers only, like from address, to address, action name etc.
3.How is the Dispatch API related to Asynchronous communication if they are talking all the time about dynamic clients?
Future<?> response = dispatch.invokeAsync(T, AsyncHandler);
invokeAsync method is a polling method. The response, returns to the user immediately and may be polled for completion. In the meantime, the client program can do other work.The javax.xml.ws.Response implements the java.util.concurrent.Future interface that is included in J2SE 5.0. The Response object returns the actual response via its get method, which blocks if the response is not ready to be returned.
4.The 2 usages modes of the Dispatch API(MESSAGE and PAYLOAD), what are used for, and how are they related to the Asynchronous communication model of JAXWS?
Messaging modes are not directly related to asynchronous communication. The messaging modes define the amount of information sent in the web service request.
MESSAGE MODE can only be used if SOAP binding is used.
Is it possible to send "100 Continue" HTTP status code, and then later some other status code after processing entire request using Java Servlet API (HttpServletResponse)?
I can't find any definitive "No" answer, although API doesn't seem to support it.
I assume you mean "100 Continue".
The answer is: no, you can't (at least not the way it's intended, as provisional response). In general, the servlet engine will do it automatically, when the request requires it. Of course this makes it impossibe for the servlet to prevent sending the 100 status -- this issue is a known problem in the Servlet API, and has been known for what feels like eons now.
I know that Jetty will wait until getReader() or getInputStream() is called before it sends a 100. I think this is the behavior you are looking for. I don't know what Tomcat does.
Did you mean to ask How do I send a status code before the complete request is received, to interrupt an in-progress request due to a missing header field? It seems that's not possible with standard servlets.
What server are you using?
Some server's servlet extensions may allow this, e.g. Tomcat's Comet servlet might send EventType.BEGIN once the headers are available to process, which may allow you to interrupt a PUT that doesn't have the correct authentication.
Alternatively your server might have a plugin to reject requests based on headers.
Do you mean status code 100 ?
The API does support sending SC_CONTINUE.