Normally, when we use HTTP requests, we have a specific set of methods/callbacks that would be called when the request succeeds/fails. Each connection request could have its own callback methods, which made structuring of code very easy.
So now that I am trying out Socket.io for a new project, I got all confused. For instance, you emit a message into the socket connection and you're done. no callbacks there. There is no easy way I can know if that actually succeeded or not I've managed to simulate a callback by writing this method:
public void emitRequest(final String event, JSONObject data, final emitResponseListener pListener)
{
mSocket.on(event+"_resp", new Listener() {
#Override
public void call(final Object... args) {
((Activity)c).runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
if (pListener!=null)
{
pListener.onResponseRecieved(data);
}
}
});
}
});
mSocket.emit(event,data);
}
This method listens for a event_resp message from the server after emitting an event. But thats as far as I've got. I have no clue as to how to handle errors for specific emits, so as to update the UI or inform the user .etc.
Sure, there are callback events for the Socket but those are impossible to wire up into the apps flow.
So does anybody know a way to achieve this? I searched a lot but couldn't find anything. I'm using Java Client but generalized answers for any client API are welcome.
You have to change your view - instead of callbacks think about events, and base your design accordingly.
When you make a request to the socket server, generate a unique token. Send the token to the server and have the server send it back with the request response. Using the token you can register a callback that will fire for event matching the request response event and this token.
This way you can execute the calls one after another.
To Cover cases where the server did not return a response, we use timeouts of 30 seconds. About 99.9% of the times we didn't get a response happened due to socket disconnection, so the socket error callback handled that after successful reconnection, without reaching the timeout.
Related
I have a #ServerEndpoint running on Jboss which holds websocket connections. The customer doesnt want the push of data to be done through the #ServerEndpoint´s #onMessage, but rather a POST-request to some REST endpoint which then pushes the data to the websocket connections (yes, I dont get it either). So my question is; can I get hold of the websocket sessions from the REST-endpoint without opening a server to server connection to the #ServerEndpoint (cause then the security context of the user is broken)?
So I need something like this:
#Controller
#Path("/path")
public class WebsocketController {
#GET
public void doPost(String text) {
//somehow get all websocket connections to the #ServerEndpoint
//then for all sessions do:
session.getBasicRemote().sendText(text);
}
}
Really what any sensible solution would put in the #OnMessage method of the #ServerEndpoint
I ended up with a syncronized list of Sessions I maintain on #OnOpen og #OnClose which holds all open connections. Then I push to these connections from the REST endpoint.
I was trying to follow along with one of the Dart HttpServer examples from GitHub, and, while it does show how to create and handle routes, I'm still at a loss on how to produce and send an HttpResponce in response to a specific url being requested.
For example, while working with WebAPI, I would have an Api Controller, in which I could explicitly define an action for GET, PUT, DELETE and POST verbs, and return an appropriate HttpResponse with a resource from each such method.
Does anyone know how this typical CRUD business is done using Dart as an Http server?
Once you receive a HttpRequest you need to use the response attribute to answer.
void sendOk(HttpRequest request, [content]) {
request.response
..statusCode = HttpStatus.OK
..write(content)
..close()
;
}
I have an REST server as backend, it provides a set of services, also, it uses basic authentication method for access.
Now I need to create an GWT frontend,so, I need to perform http calls to the REST backend from the GWT frontend
After some research I found the HttpBuilder to handle http requests to the backend, but it seem to be a pain when trying to perform cross-site requests, and also it comes with some restricions related with Safari browser.
Then I found this https://developers.google.com/web-toolkit/doc/latest/tutorial/Xsite article, where it talks about an "Proxy on your own server", so it looks to be the solution I was looking for, but I did not find more information, or an example. It says that I could create server-side code to download the data from remote server (backend), so, should I create a http client like the apache client on server-side code, and implement a set of services that use it to make request to the backend?, if yes, how to handle the user authentication and the session? if not, give me a light please.
Thanks
it seem to be a pain when trying to perform cross-site requests,
Actually you can make Cross Site Requests from GWT RequestBuilder if we can set in Servlet Response Header
Response.setHeader("Access-Control-Allow-Origin","http://yourrestserviceur.com/url");
should I create a http client like the apache client on server-side code, and implement
a set of services that use it to make request to the backend?
No, it is not required. use RequestBuilder
RequestBuilder Example:
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
displayError("Couldn't retrieve JSON");
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
updateTable(asArrayOfStockData(response.getText()));
} else {
displayError("Couldn't retrieve JSON (" + response.getStatusText()
+ ")");
}
}
});
} catch (RequestException e) {
displayError("Couldn't retrieve JSON");
}
What is difference between a navigation in JSF
FacesContext context = FacesContext.getCurrentInstance();
context.getApplication().getNavigationHandler().handleNavigation(context, null, url);
and a redirect
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.sendRedirect(url);
and how to decide when to use what?
The issue with navigation is that page URL does not change unless faces-redirect=true is added to the query string of the navigation URL. However, in my case appending faces-redirect=true throws error if I want to redirect to a non-JSF page like a plain HTML page.
And another option is as BalusC suggested at JSF 2.0 redirect error
First of all, the term "redirect" is in web development world the action of sending the client an empty HTTP response with just a Location header with therein the new URL on which the client has to send a brand new GET request. So basically:
Client sends a HTTP request to somepage.xhtml.
Server sends a HTTP response back with Location: newpage.xhtml header
Client sends a HTTP request to newpage.xhtml (this get reflected in browser address bar!)
Server sends a HTTP response back with content of newpage.xhtml.
You can track it with the webbrowser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.
The JSF navigationhandler doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.
Client sends a HTTP request to somepage.xhtml.
Server sends a HTTP response back with content of newpage.xhtml.
However as the original HTTP request was to somepage.xhtml, the URL in browser address bar remains unchanged. If you are familiar with the basic Servlet API, then you should understand that this has the same effect as RequestDispatcher#forward().
As to whether pulling the HttpServletResponse from under the JSF hoods and calling sendRedirect() on it is the proper usage; no, that isn't the proper usage. Your server logs will get cluttered with IllegalStateExceptions because this way you aren't telling JSF that you've already taken over the control of the response handling and thus JSF shouldn't do its default response handling job. You should in fact be executing FacesContext#responseComplete() afterwards.
Also, everytime whenever you need to import something from javax.servlet.* package in a JSF artifact like a managed bean, you should absolutely stop writing code and think twice if you're really doing things the right way and ask yourself if there isn't already a "standard JSF way" for whatever you're trying to achieve and/or if the task really belongs in a JSF managed bean (there are namely some cases wherein a simple servlet filter would have been a better place).
The proper way of performing a redirect in JSF is using faces-redirect=true query string in the action outcome:
public String submit() {
// ...
return "/newpage.xhtml?faces-redirect=true";
}
Or using ExternalContext#redirect() when you're not inside an action method such as an ajax or prerender listener method:
public void listener() throws IOException {
// ...
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/newpage.xhtml");
}
(yes, you do not need to put a try-catch around it on IOException, just let the exception go through throws, the servletcontainer will handle it)
Or using NavigationHandler#handleNavigation() in specific cases if you're using XML navigation cases and/or a custom navigation handler with some builtin listener:
public void listener() {
// ...
FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler nh = fc.getApplication().getNavigationHandler();
nh.handleNavigation(fc, null, "/newpage.xhtml?faces-redirect=true");
}
As to why the navigation handler fails for "plain HTML" files, that is simply because the navigation handler can process JSF views only, not other files. You should be using ExternalContext#redirect() then.
See also:
How to navigate in JSF? How to make URL reflect current page (and not previous one)
When should I use h:outputLink instead of h:commandLink?
I'm doing a university project in which i have to communicate with an existing server using SIP messages. I have done the part where i send the message, and i see with wireshark that the server responded, but i don't know how to receive that message and interpret it.
I have created a class that composes a sip message, and then creates a UdpTransport to send the message. I fill all of the message headers manually before that.
udp_transport = new UdpTransport(0, this);
udp_transport.sendMessage(sip_message, new IpAddress(toAddress), 5060);
Now i wonder how to receive the message the server sends back.
The declaration of MjSip SipProvider class (i modeled mine after it, they both call UDPTransport) implements TransportListener and has a callback methond onReceivedMessage()
but i'm not sure how to make it listen. I need to listen on a specific port, that the user inputs in the UI before. Not really sure how this callback even works.
So, i just need something to listen for a response message, and that it calls my processReceivedMessage() method so i can extract information.