Socket.IO client event handler not called? - socket.io

I'm an iOS developer who recently started using Socket.IO. During the life cycle of my iOS application, my server will be receiving messages from my app as the client, but for one particular case, the server will also need to receive a message from a web browser as the client. I'm testing a very basic browser UI, which includes a text field and a button and on the tap of that button, a numeric code (which was entered in the text field) needs to be sent to the server. This is what that looks like:
<form>
Code:<br>
<input type="text" id="code" name="code"><br>
<input type="submit" id="validatebutton" value="Validate">
<script src="/socket.io-client/dist/socket.io.js"></script>
<script>
document.getElementById("validatebutton").onclick = function() {
var socket = io('http://localhost:3000');
socket.on('connect', function(clientSocket) {
clientSocket.emit('validateCode', document.getElementById("code"));
});
};
</script>
</form>
The connection works fine. When I run this code, the client successfully connects to the listening socket server. The only problem is that the event handler is not executed. I may be very off here, but what I went for is a client event handler, which is included in the Swift SDK:
self.socket.on(clientEvent: .connect, callback: { (data:[Any], ack:SocketAckEmitter) in
// Do something here
})
self.socket.connect()
I'm just assuming that the Javascript client has a client event handler (named 'connect') as well, which is received by the client at the moment of connecting to a server. Like I said, I may be way off here. I'm just following the Socket.IO documentation posted on their website, which tells me to do it this way. If someone can tell me what I'm missing, or what I'm doing wrong, it would be much appreciated. Sorry for all the noobishness, but I really don't know where else to turn, since the official documentation is very vague and the other question on Stack are a little too advanced for me.

I wouldn't put the emit function inside the connect. Try emitting like below in your client
<script>
var socket = io('http://localhost:3000');
document.getElementById("validatebutton").onclick = function() {
socket.emit('validateCode', document.getElementById("code"));
};
</script>
Your click event was probably getting executed, but the emit was not due to it being wrapped in the connect function (which only gets executed when the socket connects to the server)
Also I would put the JavaScript in its own file, but for now, at least after the form (not inside it) will work.

Related

Laravel Notification System

I use a simple Query Code to display Toastr in my application. This is the code:
<script>
document.getElementById("test").onclick = function() {
$.toaster({
priority : 'success',
title : 'yassine Jennane',
message : 'yassine jennane test toster'
});
};
</script>
My problem is when there is another user connected in my application, he isn't receiving the notification at the same moment as the first one do. Why?
Link of the notification script + demo: jQuery & Bootstrap Based Toast Notification Plugin
This won't work like that. You need to create Event Classes and Broadcasting Channels. Further you need to have some socket.io node.js side so that the notifications are shown live on the client side.
You probably don't have experience in this subject, so I would suggest to do following things:
Have a look at following in the documentation: https://laravel.com/docs/5.7/broadcasting
Watch following tutorial on laracasts: https://laracasts.com/series/real-time-laravel-with-socket-io/episodes/1
Of course you can have a look at some other tutorials you find on the internet.
The plugin you're using is a Jquery plugin that makes toasts in user browser, it works only for connected user, if you want to show notification for all the users using your application, you should use Cloud Messaging service, Firebase is good one.

An ajax call to a url that opens socket.io connection - fails

I have a node.js server running. It accepts messages via socket.IO.
I need to send messages to the server from some device. This device supports Javascript, but does not support socket.IO commands (it's strange, but that's what I have).
I tried to work around it in the following way:
On my server I put a send.html file that sends a socket.IO message:
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io('http://localhost:3000/');
socket.emit('message', 'messages sent');
</script>
If I just call this file (localhost/send.html) then everything works fine.
Then I try to call send.html via ajax from the device:
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://localhost/send.html", true);
xmlhttp.send();
</script>
and.. nothing happens.
If I try to call any other .html file from the device, then it works. This makes me think that a socket.IO connection cannot be opened by a file that was called by ajax.
However I couldn't find this fact anywhere and anyway, I still need to find a way to send data from the device to socket.IO.
Does anyone know how to solve this problem, or can think of an alternative solution?

How to update the contents of page at the same time using ajax?

example: There are two tabs in browser which are displaying the same page.. now the problem is when i update the content of first tab using ajax the result will only be visible in the next tab after reloading the page..
How to make it work without manually refreshing the page?
You can use Websocket for that. There is a websocket implementation for node.js javascript called Socket.io. By using this, instead of pulling data from server, you can notify all the client connected to your server. Here is a simple implementation:
Client:
<script src="path_to/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://your_rest_server');
socket.on('update', function (response) {
document.getElementById("content").innerHtml = response.data;
});
</script>
Server:
io.sockets.on('connection', function (socket) {
socket.emit('update', { data: 'New content' });
});
In above script, server sends update to all clients to connected in a box called "update". Servers already listens box called "update". When any new content has arrived, it put data to specified html area
You can see more detail here

Flex BlazeDS detect browser close

I have a Flex application that connects to a BlazeDS server using the StreamingAMF channel. I want to detect on the server side in case the browser is closed. I have added an implementation for FlexClientListener & registered it to the FlexClient (FlexContext.getFlexClient().addClientDestroyedListener)
But the clientDestroyed method of Listener is not invoked on browser close. It gets invoked on Session timeout. Is there any other way to achieve this?
You won't be able to detect browser interactions on a client from the server.
Your best guess is to make use of ExternalInterface. It allows your Flash app to communicate with JavaScript, and vice versa.
Use the JavaScript onClose event to trigger some JavaScript which will call a function in your Flash App which will make a remote call to let your server side know that the browser is being closed.
We too had similar issue, not closing the session was causing memory leak in BlazeDS, We wrote the below script in swf wrapper javascript, to make ensure that closing browser invokes session closure code in flex
<script language="JavaScript" type="text/javascript">
function cleanup()
{
getMyApplication("swf_filename_without_extension").cleanUp();
alert("Disconnected! Press OK to continue.");
}
function getMyApplication(appName)
{
if (navigator.appName.indexOf ("Microsoft") != -1)
{
return window[appName];
}
else
{
return document[appName];
}
}
</script>
<body onbeforeunload="cleanup()">
In Flex add a call back on creation complete listener
ExternalInterface.addCallback("cleanUp",cleanUp);
and write all your session closure code in cleanUp method.
Note: don't forget to put the alert message in javascript. That will give enough time for cleanUp method to execute.

Pusherapp/Websocket not connecting

I'm trying to use pusherapp here but chromium's console just gives me "WebSocket is closed before the connection is established." My JS is below, any ideas as to what might be the problem?
<script type='text/javascript'>
$(document).ready(function(){
var pusher_key = "<%= Pusher.key %>";
var pusher_channel = "thirsty-<%= Rails.env %>";
var pusher = new Pusher(pusher_key, pusher_channel);
pusher.bind('push_comment', function(content) {
comment_html = '<li><p>' + content + '</p></li>'
$(comment_html).prependTo('#comments');
});
});
</script>
The question is asking the reason for the following error:
WebSocket is closed before the connection is established.
This is actually a generic WebSocket error which is logged by the browser when an attempt is made to close the WebSocket connection (by calling webSocketInstance.close()) before the connection has even been established.
The error is triggered by the Pusher JavaScript library try to close a connection, but is caused by bad network or browser conditions (e.g. online/offline reporting). All all cases (that I'm aware of) the Pusher JavaScript library will retry connecting until those connections are resolved (e.g. the Internet connection is restored).
More information and an example in the following answer:
What does "WebSocket is closed before the connection is established" mean?
A couple of points on the code above:
the Pusher constructor has a first parameter which is the application key. The second parameter is a map of key value options. So, you shouldn't be passing in a channel name as the second parameter. More info on the Pusher constructor here
The pusher.bind call is actually deprecated (docs being updated now). For channel events you should bind directly on the channel using channel.bind and for connection events you should bind on the Pusher.connection object.
It could happen if the internet connection is too slow or disconnected.
Cross check the pusher Credentials.
It you have cluster in pusher channel app make sure you write it in you code.

Resources