JavaScript Websocket Own Close Code - javascript

I have run in to the following problem:
For a customer I have to be able to open websocket connection to different websockets, depending on the current view.
The Connection & Message Handling is no issue & is all working as intended.
However, I wanted to implement a function that closes the open websockets when switching views, so they don't stay running for no reason.
I do this through the following code :
$scope.closeOpenWebsockets = function () {    
var  socketLength  =  $scope.openWebsockets.length;    
while (socketLength--) {      
console.log($scope.openWebsockets[socketLength]);
 $scope.openWebsockets[socketLength].close(4999);    
}    
 $scope.openWebsockets  =   [];
};
$scope.addOpenWebsocket = function (socket) {    
 $scope.openWebsockets.push(socket);
};
This does work, the only thing I can't get working is changing the close code of the websocket.
Based on the list I found here :
https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
I tried using various codes listed there, but none seem to work. everytime I call the .close() myself, the close code I get back is 1006. Above example is with 4999, a close code normally available for applications. But also did not work when trying to send for example 1000.
The reason I need this is because the connection can also be closed from the other side, & in this case I need to try and reconnect. (It's always a close event & not an error event).
I hoped to do this based on close code, but I wanted to choose the code I sent when closing manually so that I am sure I'm not blocking any other close codes I might receive (I can only do limited tests with the source system & thus I am not 100% sure of all possible codes I might receive)
As probably visible in the code, I'm doing this in AngularJS.
Am I missing something here? I have looked through numerous stackoverflow posts/websocket guides and so on. But I haven't found anything.
Edit : This was one of the guides I found:
https://www.tutorialspoint.com/websockets/websockets_closing_connection.htm

Related

Control browser javascript execution from command line

I want to refresh a page in a browser tab using keyboard shortcut or CLI command when the browser window is not active (i.e. I'm working on different display). The webpage that have to be refreshed is well under my control, so I can inject any javascript there. Scrolling location should be kept after the refresh. My idea is to include simple javascript on that page that will wait for some outside event, i.e. through socket, and when this event happens, run location.reload(true). Then I can communicate with this javascript from the command line (shell) script and assign keyboard shortcut to this command line script if needed. I'm pretty sure it's possible because there are lots of tools that allow this (e.g. LiveReloadX). I cannot use such tools because I don't want to automatically refresh the window when something changes, I want to do it by explicit command. It seems that it should be really simple, but I cannot find the solution so far. So, my question is: how to make javascript running in the browser to be controlled from the command line?
There's two parts to getting your solution done - the server running on your command line and the client running on your webpage.
Client
In your browser, you want to initialize a WebSocket client. MDN has a great example to get started with this, and I added your intended functionality of refreshing the page:
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
location.reload(true)
});
Server
There are many different ways to set up a WebSocket server and choosing the one that works best for you is probably too broad for an answer on this site. I did some quick research, and it looks like websocketd is a great way to wrap an existing command line program that uses standard in/out into a WebSocket server. You would need to implement a command line program that listens for your refresh shortcut and then writes a message to standard out. Then, you would wrap it with websocketd and run it from the command line:
websocketd --port=8080 ./your-shortcut-listener.sh

Push notifications, where are they?

I had to include some js from a large company that's doing business with my employer. Apparently that js includes push notifications.
The page I'm making now asks "would you like to receive notifications?". How can I, in Chrome, find the line of code that's causing the prompt?
I've opened up devtools and searched for "notification" "subscribe" "pushmanager" etc in the "search all files" function & don't see it in there. I just want to know what they're making us include.
You should look for push notification subscription code. It should look like this:
serviceWorkerRegistration.pushManager.subscribe()
Search for one of these terms and you should find the piece of code you are looking for.
Assuming the other answer is correct (I honestly don't know)..
var swr = serviceWorkerRegistration.pushManager.subscribe;
serviceWorkerRegistration.pushManager.subscribe = function(){
swr();
console.log((new Error()).stack);
};
This should print the stack trace in the console whenever that function is called, allowing you to find the origin script and line numbers and stuff..

WebRTC, JS, node.js App working locally through remote server but not different connections

I have recently started to look at inter-browsers communications, and got paricularly interested in webRTC. I am trying at the moment to build a file transfer through a Data Channel with the beginner oriented library provided here :
https://github.com/muaz-khan/WebRTC-Experiment/tree/master/DataChannel .
My application is visible here : https://shirase-ttt.jit.su/Dropzone.html
It does a basic file transfer on drop of a file. The problem is, it works between 2 tabs of your own browser (Chrome tested only, but different locations). But as soon as you try it between 2 different internet connections/locations, it stop working. The channel is established but the file isn't sent. I have no idea where I should start looking, the code seems fine, as it works locally (test yourself, see steps below) but I can't swear I haven't made a mistake, would anybody help?
Steps for testing :
Open https://shirase-ttt.jit.su/Dropzone.html on 2 tabs of your browser / 2 browsers.
Tab1 creates a channel name and clicks Connect.
Tab2 enters the same channel name and clicks join.
After a few seconds, you should see all the Channel info in the console. From this point on, you can drop a small file in the box of any client, and see it downloading through the console of the second client. I use a ~100kb image, which takes about 15seconds to dl. It is quite impressive.
I then tested with a friend remotely. After establishing the channel. You see the file being sent, but nothing is received.
The code :
Client : https://github.com/xShirase/RTC-Exploring/blob/master/Dropzone.html
Server : https://github.com/xShirase/RTC-Exploring/blob/master/ttt.js
on the server, only lines 1-34 are relevant, the rest is for different works. Yes, I have tried stripping it naked. No, it doesn't change anything.
Any ideas are welcome. Thanks. I'm thinking it may be an issue with the hosting, maybe https redir messing up things? I don't know, to be honest. Which is why I write here.
Also, I have another request. The web is at the moment undergoing a revolution in many ways. we have the chance to find ourselves at the very beginning of the curve, where everything is still to do, but enough is done to have some fun. So I'd like to put up a team of people, not professionals, but who are eager to learn as much as they can and do as much as they can to push in the right direction. The point I'm personally at is : Good understanding of sockets, good scripting skills, not pro enough I guess, and lots of ideas. I wanna explore webRTC, understand it properly as it evolves, and participate to this evolution. I'm sure I'm not the only one, so to anyone interested and with similar motivations, let's learn faster by working in groups. Contact me.
Disclaimer : The second part of this post may not be in the right website, I'm not sure. But it's where it can be seen, and that's what I'm looking for. Nothing professional or any obligations of any kind, just code, test ideas, that sort of things. If anyone has issues with that part, edit, flag, downvote, or maybe talk first ;-)
Thanks.
It is NAT traversing issue. DataChannel.js used "only" STUN. Now, it is fixed because using two TURN servers, too. If it is still failing for your; try to use "your own" TURN server.
STUN = {
url: !moz ? 'stun:stun.l.google.com:19302' : 'stun:23.21.150.121'
};
TURN1 = {
url: 'turn:73922577-1368147610#108.59.80.54',
credential: 'b3f7d809d443a34b715945977907f80a'
};
TURN2 = {
url: 'turn:webrtc%40live.com#numb.viagenie.ca',
credential: 'muazkh'
};
iceServers = {
iceServers: options.iceServers || [STUN]
};
if (!moz && !options.iceServers) {
iceServers.iceServers[1] = TURN1;
iceServers.iceServers[2] = TURN2;
}

What is the best way to implement idle time out for web application (auto log off)

I want to implement an idle time-out for the web application that we are building. I had earlier achieved this using AsynchronousSessionAuditor from codeplex, which essentially looks for the formsauthentication and session cookie timeout by constant polling.
But it has a draw back of not respecting the client side events, it will look for only last postback to decide when to log off.
The jquery plug jquery-idle-timeout-plugin from erichynds solves this issue of client side events but suffers from another drawback that is not able to recognise user is active on some other tab.
Is there anyone already fixed the TABBED browsing issue with jquery-idle-timeout-plugin already? Or is there any better approach of application time out for web applications (by the way this web app is build using asp.net f/w)
If I understand your question right, it is not possible, since there are no events triggered in javascript for activity outside of the current window/tab.
Unless you have a addon to go along with your website for each browser, which could monitor all activity in the browser, but that is not really a practical approach.
Well, you'd have to code it by hand, which is not really hard. You can use the onfocus and onblur functions to do something like this:
$(function() {
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
showIsActive();
});
function showIsActive()
{
console.log(window.isActive)
window.setTimeout("showIsActive()", 2000);
}
function doWork()
{
if (!window.isActive) { /* Check for idle time */}
}
If you make a little search you can find that varaieties of this question have already been asked and answered, you can probably find a solution you can implement with one of the plugins you mentioned.
Try:
Run setTimeout only when tab is active
or
How to tell if browser/tab is active
EDIT--> ADDED:
Or I'd try a different approach. You could create a cookie with some hash and save that hash in your DB with a timestamp that updates whenever the window is active (you could check every 5 seconds or something, it's not an intensive request)
Then, do another check before(but in the same request) to see how much time has passed since the last timestamp and log them out if necessary.
it won't log them out isntantly when time has passed, but it will when they try to access the site either by opening it again or by focusing on the tab/window.

Best practice for a practical real-time app with .NET MVC4

Hello people and bots,
I'm developing the front-end web application for a system and have hit a little problem.
The whole application has to be on one page, meaning no refreshes or page changes during the flow of the major areas of the application.
It also has to work in all web browsers including IE7 and be deploy-able as a HTML5 application for tablets and mobile phones.
It's based around a user logging in, which is regulated by webforms authentication, then I need to poll or long-poll the server for updates. This would be simple if I could do a request for each part of the system, however if the system gets too big session blocking becomes a problem and it could also end up ddosing itself. So what I need to do is think of a way to send one request and build one response from that request.
My first idea was to build a response model with JSON or XML and let JavaScript regulate what needs to be updated. For example, a new comment has been made on a topic, all the clients see this update near instantly. My idea was to send something like this:
[
'd':
{
'addComment' : [{'topicId':'topic1', 'description':'haha'}, {'topicId':'topic1', 'description':'lol'}],
'addTopics' : ['topic2','topic708'],
}
]
JavaScript would then parse this and add "haha", and "lol" to the element with the id "topic1". In theory it seems quite simple to achieve, but as the system is getting bigger it seems to constantly be turning into a big mess.
My second idea was to simply have a set of client-side functions for adding and removing stuff in the DOM, And then use a JSONP technique to call this function.
var addComment = function(commentModel)
{
var topic = document.getElementById(commentModel.topicId),
comments = topic.getElementByClassName('comments')[0],
comment = document.createElement('div');
comment.innerHTML = commentModel.description;
comments.appendChild(comment);
updateUnreadComments();
}
Response:
(function(addComment){
addComment({ topicId : 'topic1', description : 'haha' })
addComment({ topicId : 'topic1', description : 'lol' })
})(addComment)
Personally I find both methods a rather annoying workaround for nothing more than simple broadcasting.
I was wondering if anyone else has ever had the same problems and if they have ever come up with a more creative solution.
I would also like to know what kind of security issues I could expect with JSONP.
All help is appreciated!
You may take a look at SignalR. Scott Hanselman also blogged about it.

Categories

Resources