Socket.io not listening - javascript

im using this simple code
Client.html
http://pastebin.com/c1C2F9MQ
Server.js
http://pastebin.com/Cqjhjfwm
Everything working fine till the last step of my client code
socket.on('add', function(data) {
socket.broadcast.emit('AAA');
});
It seems that the socket add never comes but on my server I have
socket.on('Text', function(data) {
socket.emit('add', data);
});
And I tested if socket text was coming and it does, I cant find the problem
Thanks

socket.broadcast.emit sends message to all sockets connected to server except the concerned socket. So most likely add does come to server but it broadcasts AAA which your client cannot get. Use io.sockets.emit to send to all connected sockets. Change this
socket.broadcast.emit('AAA');
to
io.sockets.emit('AAA');
Update
I too overlooked that you are calling socket.broadcast.emit from client not from server. It would have shown error on browser console, since broadcast is absent on client.

Currently your on('add') code on the client side is within the on('connect') event which is not correct...
You need to take it ouside there, so it becomes:
socket.on('connect', function () {
$('#button').click(function() {
var addtext = $('#text').val();
socket.emit('Text', addtext);
});
});
socket.on('add', function(data) {
socket.emit('AAA');
});
EDIT: I also just noticed you had socket.broadcast.emit() in your client side code. As far as I know there's no concept of broadcasting from the client. If you want to broadcast something then the client should send it to the server then the server broadcasts to the other clients.

Related

io.emit() not emmiting data to all clients

I am creating a chat application.
In the server, we had an event.
io.emit('userAgentConnectMsg', data);
In the client, we are listening to this event.
socket.on('userAgentConnectMsg', (data) => { console.log(data)} );
Suppose think I have two clients connected to server.
If one client gets message another client will not get that.
This is happening randomly.
I changed code from io.emit to io.sockets.emit still the same issue.
And the worst thing is I am not getting any error either from client or server.
And I am not at all sure where the issue is happening from either it is from server or client.
I did some analysis for socket io before the io.emit
I logged io.sockets.adapter.sids which basically return all connected socket ids.
the issue is sometimes it shows only some sockets and sometimes it shows empty object.
Some can help me if you have faced the same issue.

Node JS socket.on() client side glitch?

I am learning Node JS and have come across some strange behavior which perhaps someone knows the answer to. A lot of tutorials posts I have come across are saying to use "socket.on('connect', function(){ blah blah }); on the client side to send a request to the server. Esentially this is supposed to stop a call from being sent to the server until the server has established a connection with the client. However when I test the code, it works as long as the client html is run first, and then node js is launched afterwards. If node js is running the server code first, and then the client side html is launched, the emit function doesn't call out to the server for some reason. If I omit the socket.on function and go straight to my socket.emit function, the server receives the emit function from the client. If node js is not running first, the client side html continues to run until node js launches the server script, at which point the client connects, and emits the request automatically. Does anyone know why this is happening? As I said, I am still learning Sockets and Node JS, so I would rather understand the behavior instead of just continuing on with my coding, even though I got it to work. Any information you provide would be extremely valuable. Thanks.:)
// Server side
var express = require('express');
var socket = require('socket.io');
var app = express();
var server = app.listen(1111, function(){ console.log("Server Listening"); });
var io = socket(server);
io.on('connect', function(socket) {
socket.on('Contact', function(data) {
socket.join(data);
console.log(data); // just to test if data is sent
});
});
// Client in head section
<script src = "https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
<script type = "text/javascript">
var socket = io.connect("http://localhost:1111");
function Setup() { // called when page has loaded
//blah blah blah lots and lots of code
var data = "blahblah"; // room to join
socket.on('connect', function(){
socket.emit('Contact', data);
});
}
// If I remove the socket.on function it works flawlessly everytime. Left in, it will only fire if the
// node js server file is launched after the client launches
It seems like you're calling the Setup() function manually some time later (in the page load event perhaps, based on the comment). This means you're creating a race condition: If the server connects before the page load event, the connect event happens too fast and you attach your listener only after it happens.
So essentially what's happening is this:
First Case (server starts after client)
Client HTML loads, script executes
Client starts attempting connection to server
Client assets finish loading, Setup() is called
Client connect listener attached to socket
Server starts up, starts accepting connections
Server accepts client connection
Client connect listener fires, emits Contact event
Second Case (client starts after server)
Server starts up, starts accepting connections
Client HTML loads, script executes
Server accepts client connection
There is currently no connect listener, so nothing happens
Client assets finish loading, Setup() is called
Client connect listener attached to socket
Silence...
To fix, you should only call io.connect(...) in the same scope that you add listeners to it. This means either moving the socket.on('connect', ...) outside of Setup() or moving the io.connect() inside Setup() (probably better).

Try to connect to a server with Google Assistance App

I need to send data out from my google assistance app to a database. In order to do this, I've created a server that takes the data, packages it, and then sends it out. I have the hostname and port and it works in a normal javascript/node.js program but when I use it in my google assistant app nothing happens. I tried figuring out the problem and it looks like the code just isn't connecting. The code I'm using to send data to the server is as follows:
function sendData(app){
var net = require('net');
var message = {"test": 200};
var thisMessage = JSON.stringify(message);
var client = new net.Socket();
client.connect(<port>, '<hostname>', function() {
app.tell(JSON.stringify(client.address()));
console.log('Connected');
client.write(thisMessage);
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
return 0;
}
(NOTE: Port and hostname left out for privacy purposes)
This completely skips over the app.tell, leading me to believe the connection is never made. I know it works asynchronously with the server, however, I don't understand why it isn't connecting whatsoever.
I have tried it both in simulation and on my smartphone with sandbox on and off. Is there a better way to connect? Note that the server I'm connecting to is python-based.
The problem is likely that you're running it on Cloud Functions for Firebase which has a limit on outbound connections under their free "Spark" plan. With this plan, you can only connect to other Google services. This is usually a good way to start understanding how to handle Action requests, but has limitations. To access endpoints outside of Google, you need to upgrade to either their "Flame" fixed price plan or "Blaze" pay-as-you-go plan.
You do not, however, need to run on Google's servers or need to use node.js. All you need is a public HTTPS server with a valid SSL cert. If you are familiar with JSON, you can use any programming language to handle the request and response. If you are familiar with node.js, you just need a node.js server that can create Express request and response objects.

socket.io 'disconnect' not called if page refreshed fast enough

I have the following abridged code:
io.on('connection', function(client) {
client.uuid = uuid.v4();
// add client object to server...
console.log('socket.io:: client connected ' + client.uuid );
client.on('disconnect', function() {
console.log('socket.io:: client disconnected ' + client.uuid );
// remove client object from server...
});
});
If I open up this page in the browser, everything seems fine. If I refresh the page, it will fire disconnect and then connection. However, if I refresh fast enough, there are times where disconnect doesn't get called and thus client data doesn't get cleaned from the server. Is there any way to protect from this?
Edit: reword reconnect -> connection
As adeneo mentioned, socket.io has heartbeats which automatically check to see if a client is still connected. The disconnect code is fired if it detects the client is actually gone. After replicating my original issue, I tried leaving the server on, and about 30 seconds later, the "dead" clients were being removed. So to solve the issue, you just have to wait. Socket.io takes care of everything on its own.
The same question was answered here.
TL;DR
You can use those options on the client:
const socket = io({
transports: ['websocket'],
upgrade: false
});
This will prevent socket.io from using the HTTP polling method at all, which causes the issues. I used this trick successfully on v4.

Whats the difference between socket.io and socket.io-client?

Whats the difference between socket.io and socket.io-client?
Some project I'm trying to use is using socket.io-client, but I'm used to using plain old socket.io, and it dons't really lay it out in the documentation.
The main difference I'm aware of is that with the socket.io-client library you can connect your server to another server serving socket.io events.
For example, if my server at http://localhost is emitting a data event, I can listen on another server like so:
var socket = require('socket.io')('http://localhost');
socket.on('connect', function(){
socket.on('data', function(data){
// Do something with data
});
});
and respond accordingly with the data object passed.

Categories

Resources