How to open and close a sockjs connection from client side? - sockjs

Currently, my client side connection opens when I refresh the page and closes when I close/refresh the tab.
I know I can close the connection from server side but I can't find it in the documentation to do so from the client side.
I want to be able to open a new connection on clicking a button, and closing the current connection on clicking another dom button.
How can I open or close a connection from the client side?
I basically want to do this;
div.col-md-6
div.btn-group.pull-right
button#button-newConnection.btn.btn-lg.btn-success(type='button', onclick="newConnection()") New Connection
button#button-closeConnection.btn.btn-lg.btn-danger(type='button', onclick="closeConnection()") Close Connection
function openConnection () {
sock.connect();
}
function closeConnection () {
sock.end();
}
Thank you.

Sock.js follows HTML5 Websockets API as closely as possible. Just use .close() on the Sock.js object:
function closeConnection () {
sock.close();
}

Related

Halt code's execution, but not the application

First off the code, which runs without error but isn't covering everything I need it to:
public async Task SaveData()
{
// MessageDialog restartMessage;
// ^^ This was made global and is defined in SafeToSave()
// Check if it's safe to save
await SafeToSave();
if (restartMessage != null)
{
CoreDispatcher cD = Window.Current.CoreWindow.Dispatcher;
await cD.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await restartMessage.ShowAsync();
// This WILL invoke 'Application.Current.Exit()'
});
return;
// Issue is right around here...
}
// Other code...
}
The basic premise is that if it is not safe to save, a message dialog will tell the user that the app needs to be restarted and then perform 'Application.Current.Exit()' when they then tap the 'Okay' button.
My problem is that I need my code to stop executing when that restart is hit. Right now 'return' only ends this method, but after that it will continue to do other things in the method that called SaveData() until my restartMessage takes effect, and that's not good.
I considered putting 'Application.Current.Exit()' above the 'return' statement, but that will shut things down before my error message can be seen. Which is also not good.
The other solution was skipping the whole CoreDispatcher thing and just running ShowAsync() by itself, except that would trigger a different known error. Basically I have a few MessageDialogs that call the SaveData() method and opening a MessageDialog when another MessageDialog is already open is, again, not good.
That's about it: I need something to stop my code form executing without killing the whole application or preventing my error message from displaying. What can I do?
Short version, I used this guy's solution: MessageDialog ShowAsync throws accessdenied exception on second dialog
Since I can't control when the Dispatcher is going to occur, it's necessary to scrap it. Now I said I couldn't do that because it was preventing another bug, so I used the advice in that link to prevent that bug in a different way... so now I can ditch the Dispatcher and force my application to deal with my message dialog without it continuing along its multi-threaded path and doing things it shouldn't!
Code for my solution is moved into the SafeToSave() method. I did what the guy in that link did and then changed this:
CoreDispatcher cD = Window.Current.CoreWindow.Dispatcher;
await cD.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await restartMessage.ShowAsync();
});
Into this:
await restartMessage.ShowAsync();
And unlike before I'm not getting an access error for calling ShowAsync() while another MessageDialog is already up, because I'm forcibly closing it first.

Alernative for poll in primefaces

I am using primeface 3.2. i am using ajax poll to get every reaction into th gui.But ajax poll is not get stopped.i am trying to stop in server side.
i am using stop=true to stop the poll.
Update
Here is a link to the showcase Poll - Start/Stop
Old
If you want to stop the polling from the server side you could use the *RequestContext API *
Like described by cagataycivici
look at his (old) blog post
How to Stop Polling From Server Side
Code snippet
Client
<p:poll listener="#{bean.listener}" update="sth" stop="#{bean.stop}"/>
Server
private boolean stop = false;
public void listener() {
if(condition) {
stop = true;
}
}

Chrome extension : access local storage more than once in content script

I know how to access localstorage in content script, but only one time. I access it via sendRequest, but when I try to use this method in an event function, the jvascript file doesn't even load.
Is it possible to access to the options many times, like whenever the onclick event is fired ?
I looked on the google code website and found something to create a connection between content script and background using chrome.extension.connect(). Do i need to use that ?
Thanks !
Actually you can use sendRequest as many times as you can, but if you want to do it in another way you can open a long-lived channel (or what I call, "message tunnel") between content script and background page to communicate.
In your content script, you can use
var port = chrome.extension.connect({name: "myChannel"});
to open up a channel.
Then you can use
port.postMessage({message: "This is a message."});
to send a new message to the background page.
port.onMessage.addListener(function(msg) { }) listens to a new message.
In your background page,
chrome.extension.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
if(port=="myChannel"){
console.log(msg+" from port "+port) //Gives you the message
}
})
})
listens to a new message in a specific port.

Execute exe-file from html-page?

I want to launch a local exe-file (without saving it to another location first) upon clicking on a link on a local html file.
It either needs to work in IE, Firefox, Chrome or Opera, I don't care. It's just for a presentation tomorrow.
It's simply not possible. If it was, it would be considered a security flaw and fixed. On Firefox within hours, on IE within some months.
UPDATE: You could try registering your custom protocol: http://openwinforms.com/run_exe_from_javascript.html
But I believe the browser will still prompt you whether you want to run the app.
I want to share my experience.
The accepted response says that it is not possible but it is quite possible indirectly.
If you want to execute an exe on a pc, it means that you have acces on this pc and you can install your exe on that machine.
In my case, I had to take a 3D scan from a 3D scanner via a web application. It seemed impossible at the beginning.
After lots of research, I found that we can send socket messages via javascript.
It means that if we had an application which listens a specific port, it can communicate with a website.
Let's explain how I did this.
In my web application, I created a javascript method like this :
function openCapron3DScanner(foot) {
$("#div-wait").show();
//Creates a web socket pointed to local and the port 21000
var ws = new WebSocket("ws://127.0.0.1:21000");
ws.onopen = function () {
//Sends the socket message to the application which listens the port 21000
ws.send(foot + "-" + #ProjectHelper.CurrentProject.Proj_ID);
};
ws.onerror = function myfunction() {
$("#div-wait").hide();
alert("Erreur connection scanner.");
}
ws.onmessage = function (evt) {
//Receives the message and do something...
var received_msg = evt.data;
if (received_msg == "ErrorScan") {
alert("Erreur scan.");
}
else {
refreshCurrentProject();
}
};
ws.onclose = function () {
$("#div-wait").hide();
};
};
And I created a windows forms application who listens the localhost and port 21000.
This application is hidden, only shown in icon tray.
The only thing to do is to add the application on windows startup via code on the first load to assure that the next restart of windows it will be executed and listen the port.
private static WebSocketServer wsServer;
static WebSocketSession LastSession;
private void Form1_Load(object sender, EventArgs e)
{
wsServer = new WebSocketServer();
int port = 21000;
wsServer.Setup(port);
wsServer.NewMessageReceived += WsServer_NewMessageReceived;
wsServer.Start();
}
private static void WsServer_NewMessageReceived(WebSocketSession session, string value)
{
if (value.StartsWith("ScanComplete-"))
{
//If the scan is ok, uploads the result to the server via a webservice and updates the database.
UploadImage(value);
//Sends a confirmation answer to the web page to make it refresh itself and show the result.
if (LastMacSession != null)
LastMacSession.Send("ScanComplete");
}
else if (value == "ErrorScan")
{
//If the C++ application sends an error message
if (LastMacSession != null)
LastMacSession.Send("ErrorScan");
}
else//call the 3D Scanner from the web page
{
LastSession = session;//Keeps in memory the last session to be able to answer via a socket message
//Calls the C++ exe with parameters to save the scan in the related folder.
//In could be don in this same application if I had a solution to consume the scanner in C#.
var proc = System.Diagnostics.Process.Start(#"C:\Program Files\MyProjectFolder\MyScannerAppC++.exe", projectID + " " + param);
}
}
I hope it will help.
Use System.Diagnostics.Process.Start() method.
protected void LinkButton1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("notepad.exe");
}
You'll have to use C#, but since that's on your post, it should work. You'll also need the full path, if the file is not in your environment path that's loaded in memory.
For a 'regular link' you'd still need to place this in an ASPX page.....
Click me
We're getting really fugly now though.
You can't run an exe file on a website. (First, if it's a Linux server, exe files won't run on it and second, if you're on a Windows server, your host would kill the program immediately. And probably terminate your account.)
That link (assuming it was Play Now!) will just allow your user to download the file. (C:\Program Files\World of Warcraft\ exists on your computer, but it doesn't exist on the web server.)
You could setup a custom protocol on your local OS, if it's Windows, in regedit.
Check out this and this.
Then you create a simple HTML page, and place a link, something like this :
Start!
Given that you registered your custom "presentation" protocol, and configured it correctly in the registry, the application should launch when you click that link.

Websockets Issue, Perhaps Same Origin Policy?

I have a site hosted at localhost:8000. Now, I have a server listening for websocket connections at localhost:8001. I would like my website to connect to this server through the websocket api like
var conn = new WebSocket('ws://localhost:8001');
But I get some errors in Chromium 6.0.472.62 upon calling
conn.send('something');
That looks like: Uncaught Error: INVALID_STATE_ERR: DOM Exception 11.
In Firefox 4 (4.0b8pre), I get the error:
An attempt was made to use an object that is not, or is no longer, usable" code: "11
I thought this was an issue with the handshake not supporting websocket draft76 on the server, but I am using http://github.com/miksago/node-websocket-server/tree/master/lib/ws/ which claims to support draft75 and draft76.
Also, the initial handshake seems to work fine. I can receive a response from the server upon creating the new WebSocket, however, the problems arise on the call to "send" from the client side.
Is this an issue with the same origin policy since my httpserver is on port 8000 and the websocket server is on 8001? If so, how can I work around this?
Perhaps you need to wait for the onopen event to fire?
var conn = new WebSocket('ws://localhost:8001');
conn.onopen = function (e) {
conn.send('something');
}
conn.onmessage = function (e) {
console.log('got something: ' + e.data);
}
Also, it's a good idea to hook the onclose and onerror events too.