How to send broadcast data with Web Socket Server? - javascript

I need to send data from my BE to FE when an event happen, so I have created an Event Emitter and in the Fucntion i would like to send a Broadcast message to all the client (the message is an Array of Object), this is my code but unfortunately doesn't work properly.
emitter.on('readData', function(){
wss.broadcast = function(data) {
wss.clients.forEach(client => client.send(Object));
};
});

Ok instead of broadcasting, you are defining a function to broadcast.
emitter.on('readData', function(){
wss.clients.forEach(client => client.send(Object));
});
More details here.

Related

JavaScript - How to create custom API listener for Socket.io events?

i'm trying to create custom API listener for 3-rd developers on my site. It should look like this:
// Function will be fired when any user joins to room
API.on('user-join', function(data){
console.log(data); // Data is object with user id and name
});
I have Socket.io listener too:
// This handler is fired every time when anyone joins
socket.on('user-join', function(data){
// Probably here i should call a callback to API.on('user-join') with that data object
});
How can i send callback in Socket.io handler to my custom created API? Please let me know how to do this. Thanks.
Not sure what you are trying to do, but if I understand correctly, you want to map the "on" function of the socket.io API to your API.
The best way to do this would be to implement a function like this:
API.on = (eventName, callback) => {
socket.on(eventName, callback);
}
Where eventName is a string and callback a function.
This way, you can add an event listener to your API, the same way you would with Socket.io
Eg:
API.on('testEvent', (obj) => {console.log(obj});
you are mixing things up.
your socket API will need a server-side listener independent from your socket API, that, as far as i understood, manages the IO with the connected clients, am i right?
In this case, you don't have to bind anything. You need a controller for your API sockets and your client's controller have to trigger events to those users.
a client connects to your site
a notification is received by the server
the server notifies to the API users
here's some pseudocode, please don't use it, it just illustrates a concept :D
const thrdUsers = [.....] // socket connections
const onThirdUserConnects = socket => thrdUsers.push(socket);
API.on('connect', onThirdUsersConnects);
// Then you need a broadcast function to send events to all your clients
const broadcastToAPI = (msg, val) => thrdUsers.forEach(s => s.send(msg, val));
// Your users will trigger events to your socket.io service
socket.on('whatever-event', (data) => {
//...Do stuff
// notify the API clients
broadcastToAPI('whatever-event', data);
});

socket.emit() error handling with socket.io

I am using
$('btn').click(function() {
socket.emit('load more', function (objs) {
// do something
});
});
on the client to get objects from the server.
But sometimes the connection is lost and nothing happens. How can I make error handling such that I can tell the user that the server doesn't answer instead of letting nothing happen as it is now?
Edit
So what I want is something like
$('btn').click(function() {
var emit = socket.emit('load more', function (objs) {
// do something
});
if (!emit) {
console.log("It didn't work. Maybe you lost connection or the server is not running.");
}
});
I do know that I cannot do this, but would it be possible using promises or something?
Second argument to emit is the data that we need to pass on the event 'load more'.
If you just want to server to let know that you need data, without passing any extra info, just do socket.emit('load more'). In server, listen for event 'load more' and send data to client with particular event-name. In Client, listen for the event 'event-name' and receive data in callback like,
socket.on('event-name', function(data_from_server){
//do something
});
If you want to handle the case, where server not sends any data then wait for some time after sending the event 'load mode' and handle it.

What is .on function of socket in tcp connection in Node Js

I have a quick question. Can anyone explain this
socket.on("message",function(message){})
I am trying to connect to TCP server on node.js
server.on('connection',function(socket){
socket.on('message',function(message){
console.log("got the message");
socket.sendEndMessage("hello");
}
);
} );
I need to know when socket.on("message",function(message){}) will be called.
socket.on("message",function(message){}) will be called when a socket connected to the server emits a 'message' event:
socket.emit('message', { /* an object to be sent */ });
Using socket.on method, allows you to manage how a custom or built-in received message event will be handled. If you're sending different kind of messages through the server, lets say, requestsStats and requestUsersList message types, you'll be emitting messages like
socket.emit('requestStats', { filter: statsFilter });
socket.emit('requestUsersList', { filter: userAccessLevel });
you'll need to process them on the server (or clients) using:
socket.on('requestStats', function(message){ // process message content });
and
socket.on('requestUsersList', function(message) { // process message content });
Basically, you can define custom events/messages to be sent through web sockets.

Pusher Private Channel Subscription Succeeded Callback Data

I am trying to get the data sent back from the server, after connecting to a private Pusher channel. The following code works for a presence channel:
this.presenceChannel = this.pusher.subscribe('presence-chat');
this.presenceChannel.bind('pusher:subscription_succeeded', function(data){
//I can access all of the data here as expected
console.log(data);
});
But when I try the same approach with a private channel:
this.privateChannel = this.pusher.subscribe('private-user');
this.privateChannel.bind('pusher:subscription_succeeded', function(data){
//This returns an empty Object {}
console.log(data);
});
The interesting thing is, in the POST request data I can see the data that I am trying to access, but I can't figure out why I can't access it like I can for presence channels:
{"auth":"a146722cb55df886314f:7326fb3e1c807a679b4d4d5e5742fddc121d5ec18f5f078d054962b0267972a4","channel_data"
:"{\"data\":\"test\"}"}
try binding to this event instead
'pusher_internal:subscription_succeeded'
The pusher:subscription_succeeded event is triggered following the receipt of a pusher_internal:subscription_succeeded event. The different event name is used to differentiate a public event from an internal one.

Socket IO send to specified user ID

I want to send data to the specified user, and no one else.
currently to broadcast to everyone I do:
socket.on('newChatMessage', function (message) {
socket.broadcast.emit('newChatMessage_response', { data: message});
});
now what I want to do is simply something like:
socket.on('newChatMessage', function (message) {
socket.to(5).send('newChatMessage_response', { data: message});
});
to(5) would be the user with the ID of 5.
I think the missing piece for you is inside this function: io.sockets.on('connection', function(socket) { ... });- That function executes every time there is a connection event. And every time that event fires, the 'socket' argument references a brand new socket object, representing the newly connected user. You then need to store that socket object somewhere in a way that you can look it up later, to call either the send or emit method on it, if you need to send messages that will be seen by only that socket.
Here's a quick example that should get you started. (Note: I haven't tested this, nor do I recommend that it's the best way to do what you're trying to do. I just wrote it up in the answer editor to give you an idea of how you could do what you're looking to do)
var allSockets = [];
io.sockets.on('connection', function(socket) {
var userId = allSockets.push(socket);
socket.on('newChatMessage', function(message) {
socket.broadcast.emit('newChatMessage_response', {data: message});
});
socket.on('privateChatMessage', function(message, toId) {
allSockets[toId-1].emit('newPrivateMessage_response', {data: message});
});
socket.broadcast.emit('newUserArrival', 'New user arrived with id of: ' + userId);
});
Edit: If by id you're referring to the id value that socket.io assigns, not a value that you've assigned, you can get a socket with a specific id value using var socket = io.sockets.sockets['1981672396123987']; (above syntax tested using socket.io v0.7.9)
It's hard to say exactly how to do this without seeing your full code, but it sounds like you want to call the emit method on the individual socket you're trying to send to. If this is different from the socket making the connection (ie., a private chat partner) then you'll need some other way of storing and retrieving the correct socket you're trying to communicate with.
var sck = someFunctionToGetAppropriateSocketObject();
sck.emit('newChatMessage_response', { data: message});
see http://socket.io/#how-to-use and https://github.com/learnboost/socket.io

Categories

Resources