Open Sockjs inside an application - websocket

I want to create an application where on page3 users start communicating via a sockjs websocket (they go through page1 and page2 to reach page 3). The code is working fine but I dont know why!
// Global scope
var sock;
// Inside a function page3, this is invoked when Page3 loads for the first time
function page3(){
// Local scope
sock= new SockJS("localhost:8080/messages);
sock.onopen= function(){
....
};
sock.onmessage= function(data){
....
};
}
My question is - when a message is sent from the server how is sock.onmessage accessed by program execution even though it is 'seen' only when Page3 is loaded the first time which is when function page3() is called?

Looks like sock is not imported (the error message is saying that it is whats undefined)
Perhaps if you could share more of the code we could see why

Found my own answer.
The question is actually related to visibility of event listeners on the client. And the answer to that is - all event listeners on the client, once activated (flow of program execution having "seen" them) remain active until they are removed.
So in the above case, even though function page3() was "seen" by program execution only once - when Page3 was loaded for the first time, sock.onmessage becomes activated as a (client) event listener during that page3() function call and continues to remain active until the socket is closed.
As such, there is no need for an explicit page3() function call to trigger sock.onmessage. It (sock.onmessage) will keep listening to socket events sent by the server.

Related

XCB event loop not getting any events

I am making an addon in Firefox, so I have a ChromeWorker - which is a privileged WebWorker. This is just a thread other then the mainthread.
In here I have no code but this (modified to make it look like not js-ctypes [which is the language for addons])
On startup I run this code, conn is a global variable:
conn = xcb_connect(null, null);
Then I run this in a 200ms interval:
evt = xcb_poll_for_event(conn);
console.log('evt:', evt);
if (!evt.isNull()) {
console.log('good got an event!!');
ostypes.API('free')(evt);
}
However evt is always null, I am never getting any events. My goal is to get all events on the system.
Anyone know what can cause something so simple to not work?
I have tried
xcb_change_window_attributes (conn, screens.data->root, XCB_CW_EVENT_MASK, values);
But this didn't fix it :(
The only way I can get it to work is by doing xcb_create_window xcb_map_window but then I get ONLY the events that happen in this created window.
You don't just magically get all events by opening a connection. There's only very few messages any client will receive, such as client messages, most others will only be sent to a client if it explicitly registered itself to receive them.
And yes, that means you have to register them on each and every window, which involves both crawling the tree and listening for windows being created, mapped, unmapped and destroyed and registering on them as well.
However, I would reconsider whether
My goal is to get all events on the system.
isn't an A-B problem. Why do you "need" all events? What do you actually want to do?

Firefox Extension: responding to an http-on-modify-request observed in the parent with a message to the child frame responsible for the load

I'm trying to enhance an existing Firefox extension which relies on nsIContentPolicy to detect and abort certain network loads (in order to block the resulting UI action, i.e. tab navigation). Then handle loading that resource internally. Under rare circumstances, only after handling the load, it turns out we shouldn't have interrupted the load at all, so we flag it to be ignored and re-start it.
Under e10s/multi-process, that means the parent (where the content policy is running) must send a message to the child (handling the UI for the content) to restart the load. Today, that's done by:
function findMessageManager(aContext) {
// With e10s off, context is a <browser> with a direct reference to
// the docshell loaded therein.
var docShell = aContext && aContext.docShell;
if (!docShell) {
// But with e10s on, context is a content window and we have to work hard
// to find the docshell, from which we can find the message manager.
docShell = aContext
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem).rootTreeItem;
}
try {
return docShell
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIContentFrameMessageManager);
} catch (e) {
return null;
}
};
Which is crazy complex, because e10s is crazy complex. But it works; it generates some object in the parent, upon which I can call .sendAsyncMessage(), and then the addMessageListener() handler in my frame/child script receives it, and does what it needs to do.
I'd like to switch from nsIContentPolicy to http-on-modify-request as it presents more information for making a better determination (block and handle this load?) earlier. Inside that observer I can do:
var browser = httpChannel
.notificationCallbacks.getInterface(Ci.nsILoadContext)
.topFrameElement;
Which gives me an object which has a .messageManager which is some kind of message manager, and which has a .sendAsyncMessage() method. But when I use that .sendAsyncMessage(), the message disappears, never to be observed by the child.
Context: https://github.com/greasemonkey/greasemonkey/issues/2280
This should work in principle, although the docshell tree traversal may do different things in e10s and non-e10s, so you have to be careful there. In e10s rootTreeItem -> nsIContentFrameMessageManager should give you the MM equivalent to a frame script and topFrameElement.frameLoader.messageManager should give you the <browser>'s MM, which pretty much is the parent side counterpart to it.
Potential sources of confusion:
e10s on vs. off
process MM vs. frame MM hierarchy
listening in the wrong frame for the message (registering in all frames might help for debugging purposes)
This is the function I use to find the content message manager:
function contentMMFromContentWindow_Method2(aContentWindow) {
if (!gCFMM) {
gCFMM = aContentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDocShell)
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIContentFrameMessageManager);
}
return gCFMM;
}
So maybe get the content window that triggered that request, and then use this function.

how can i wait for javascript return before executing the second part of hub method with SignalR?

I have a problem in my ASP.NET MVC 4 project.
I use SignalR to create a turn-based game and in a hub event method OnConnected(), I call two separate methods to refresh my aspx with javascript code.
Here is my code :
public override System.Threading.Tasks.Task OnConnected()
{
// Demande les infos du joueur
Send2();
string clientId = GetClientId();
string clientName = utilisateurlambda;
if (Users.IndexOf(clientId) == -1)
{
Users.Add(clientId);
UsersNames.Add(clientName);
}
// Send the current count of users
Send1(Users.Count);
return base.OnConnected();
}
So I want the Send2() method to finish refreshing my aspx page before the method Send1(Users.Count) is called.
Actually, Send1(Users.Count) is called before Send2 finish. Please help me !
Refreshing your aspx page will kill your SignalR connection assuming you are completely reloading the same page you are starting your SignalR connection from.
Secondly, the client will not receive any messages until OnConnected completes. Typically connection initialization logic, such as adding a client to a group, goes inside OnConnected, and you probably don't want to start processing messages until your connection is initialized.
If you don't want to call Send1 until your page is refreshed, you should not call Send1 in OnConnected. Instead, call Send1 in another Hub method that you call from the client after the page refreshes.

Laravel IoC and singleton pattern

I'm trying to use Laravel IoC by creating a singleton object. I'm following the pattern from tutorial as below. I have put a Log message into object (Foobar in this example) constructor and I can see that object is being created every time I refresh page in browser. How is the singleton pattern meant for Laravels IoC? I understood that its shared object for entire application but its obviously being created every time its requested by App:make(...) Can someone explain please. I thought I would use the singleton pattern for maintaining shared MongoDB connection.
App::singleton('foo', function()
{
return new FooBar;
});
What has been said in Laravel Doc
Sometimes, you may wish to bind something into the container that
should only be resolved once, and the same instance should be returned
on subsequent calls into the container:
This is how you can bind a singleton object and you did it right
App::singleton('foo', function()
{
return new FooBar;
});
But, the problem is, you are thinking about the whole process of the request and response in the wrong way. You mentioned that,
I can see that object is being created every time I refresh page in
browser.
Well, this is normal behaviour of HTTP request because every time you are refreshing the page means every time you are sending a new request and every time the application is booting up and processing the request you've sent and finally, once the application sends the response in your browser, it's job is finished, nothing is kept (session, cookie are persistent and different in this case) in the server.
Now, it has been said that the same instance should be returned on subsequent calls, in this case, the subsequent calls mean that, if you call App::make(...) several times on the same request, in the single life cycle of the application then it won't make new instances every time. For example, if you call twice, something like this
App::before(function($request)
{
App::singleton('myApp', function(){ ... });
});
In the same request, in your controller, you call at first
class HomeController {
public function showWelcome()
{
App::make('myApp'); // new instance will be returned
// ...
}
}
And again you call it in after filter second time
App::after(function($request, $response)
{
App::make('myApp'); // Application will check for an instance and if found, it'll be returned
});
In this case, both calls happened in the same request and because of being a singleton, the container makes only one instance at the first call and keeps the instance to use it later and returns the same instance on subsequent calls.
It is meant to be used multiple times throughout the applications instance. Each time you refresh the page, it's a new instance of the application.
Check this out for more info and practical usage: http://codehappy.daylerees.com/ioc-container
It's written for L3, but the same applies for L4.

node.js event emitters binding to mulitple instances

If I have a class that listens to event emitters, is it wrong practice to bind on every instance?
function MyClass() {
emitter.on('ready', function() {
// do something
});
}
myclass = new MyClass();
If I call emitter.on() multiple times, it warns me.
(node) warning: possible EventEmitter memory leak detected. 11
listeners added. Use emitter.setMaxListeners() to increase limit.
Are event emitters meant to be bound only once per module, outside of class instances?
If this is wrong, then how do I access the class instance when events are triggered?
Thanks
The warning is that your attaching 11 event listeneres to the ready event on a single event emitter.
Generally when you listen to the same event multiple times on a single event emitter, it's likely that's a bug. For example say you have an http event emitter, if your listening on the request event 11 times that's probably a bug, you only want to listen and handle request once.
This is a debugging tool. You can get around this by doing
emitter.setMaxListeners(500); // or whatever you think is a sensible limit

Resources