Send public message including sender Socket.io - javascript

I'm starting with socket.io and I can send private messages but How I can send a message to all,
At the following code(its for test purpose) the first user receives a private message every time an user is connected , How I can broadcast all the message to all clients including the sender?
this is the client
var socket = io('http://localhost:3000');
socket.emit('user_join', { username:'{{username}}'});
socket.on('private',function(data){
alert(data);
});
socket.on('message',function(data){
console.log(data);
});
and this is the server
var connectedUsers = []
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('user_join', function(msg){
connectedUsers[msg.username] = socket;
connectedUsers['aaa'].emit('private','private message');
socket.emit('message','public message');
});
console.log(connectedUsers.keys());
socket.on('disconnect', () => {
console.log('user disconnected');
});
});

The documentation is good https://socket.io/docs/emit-cheatsheet/
There's lots of variations, but I think you're looking for:
io.emit('an event sent to all connected clients');

Related

Socket.io broadcast.emit is not working but it works without broadcast

I'm trying to send a message to everyone except the sender.
server.js
io.on('connection', (socket) => {
socket.on('typing', (msg) => {
io.broadcast.emit('typing', msg);
});
});
cleint.html
var socket = io();
socket.emit('typing', 'some message');
socket.on('typing', (msg) => {
$('#myLabel').append(msg);
});
If i remove the broadcast in server to just io.emit then it works, but the sender also sees the message.
instead of
io.broadcast.emit('typing', msg);
try
socket.broadcast.emit('typing', msg);

How client can connect to new room via socketio by leave all old rooms

i have 5 rooms on server let say "A", "B","C","D","E"
server side
i.e
io.on('connection', (socket) => {
console.log('New user connected');
socket.on('disconnect', () => {
console.log('User was disconnected');
});
});
//function that create rooms
function connectSocket(data) {
io.emit(data.device_id, data);
console.log('room',data.device_id, 'created');
}
// room creation call
connectSocket("A");
client side
var socket = io(*url*);
socket.on('connect', function () {
console.log('Connected to server');
});
socket.on(*roomname*, function (message) {
console.log(message);
});
`
problem
i want to switch room A to B
but before i switch i want to close all connections
i don't want to listen data from old rooms when i join new room
I think you mixed up events with rooms. The io.emit(data.device_id, data); doesn't create a room, it just send the data to every connected clients, the first parameter is the name of the event, the second is the data. Documentation.
The proper way to use rooms in Socket.IO is the following:
Join a room:
socket.join(roomId); // roomId is a string
Leave a room:
socket.leave(roomId);
Send to all clients in 'game' room except sender:
socket.to('game').emit('nice game', "let's play a game");
Send to all clients in 'game' room, including sender:
io.in('game').emit('big-announcement', 'the game will start soon');
For more information check the Socket.IO cheatsheet and the docs about rooms and namespaces.
I hope it helps!

losing reference to the socket in socket.io

I am having a typescript class on the server that is handling my socket.io communications that looks like below. basically it works, but ofc the server just saves the latest socket reference. (the person who last connected to the server, because the variable gets overwritten each time someone connects).
class ChatService {
private server;
private app;
private io;
private socket;
constructor(app, server) {
this.app = app;
this.server = server;
this.io = require('socket.io').listen(this.server);
this.io.set('log level', 1);
this.io.sockets.on('connection', (socket) => {
console.log('a user connected');
socket.join('test');
console.log(this.io.sockets.clients('test').length + ' - ' + socket.id);
this.socket = socket;
socket.on('message', (data) => this.onMessage());
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
}
public onMessage() {
this.socket.broadcast.to('test').emit('message', {
message: 'test message'
});
}
}
export = ChatService;
Do you have any good practise how I can have the right reference ( so that i can call socket.broadcast.to('test').emit() ). Maybe there is a way, that the client send his socket element, so that i have it on the server?
socket.on('message', (data) => this.onMessage());
Change it by this :
socket.on('message', (data) => this.onMessage(socket,data));
Then you have everything you need for broadcast and resend data.
public onMessage(socket,data) {
socket.broadcast.to('test').emit('message', {
message: 'test message'
});
}

Creating a private chat between a key using a node.js and socket.io

How do I emit a message to all users in a private chat sharing a conversation_id using node.js and socket.io?
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
conversations = {};
app.get('/', function(req, res) {
res.sendfile('/');
});
io.sockets.on('connection', function (socket) {
socket.on('send message', function (data) {
var conversation_id = data.conversation_id;
if (conversation_id in conversations) {
console.log (conversation_id + ' is already in the conversations object');
// emit the message [data.message] to all connected users in the conversation
} else {
socket.conversation_id = data;
conversations[socket.conversation_id] = socket;
conversations[conversation_id] = data.conversation_id;
console.log ('adding ' + conversation_id + ' to conversations.');
// emit the message [data.message] to all connected users in the conversation
}
})
});
server.listen(8080);
You have to create a room with conversation_id and make users to subscribe to that room, so that you can emit a private message to that room it by,
client
var socket = io.connect('http://ip:port');
socket.emit('subscribe', conversation_id);
socket.emit('send message', {
room: conversation_id,
message: "Some message"
});
socket.on('conversation private post', function(data) {
//display data.message
});
Server
socket.on('subscribe', function(room) {
console.log('joining room', room);
socket.join(room);
});
socket.on('send message', function(data) {
console.log('sending room post', data.room);
socket.broadcast.to(data.room).emit('conversation private post', {
message: data.message
});
});
Here is the docs and example for creating a room, subscribing to the room and Emit message to a room:
Socket.io Rooms
Socket.IO subscribe to multiple channels
Socket.io rooms difference between broadcast.to and sockets.in
SURE: Simply,
This is what you need :
io.to(socket.id).emit("event", data);
whenever a user joined to the server,socket details will be generated including ID.This is the ID really helps to send a message to particular people.
first we need to store all the socket.ids in array,
var people={};
people[name] = socket.id;
here name is the reciever name. Example:
people["ccccc"]=2387423cjhgfwerwer23;
So, now we can get that socket.id with the reciever name whenever we are sending message:
for this we need to know the recievername.You need to emit reciever name to the server.
final thing is:
socket.on('chat message', function(data){
io.to(people[data.reciever]).emit('chat message', data.msg);
});
Hope this works well for you.!!Good Luck

Sending message to Socket.IO via get request

I have an express node.js server serving Socket.io. I would like the ability to make get requests to the express server that will automatically send a message to a channel.
var app = require('express').createServer()
, io = require('socket.io').listen(app)
app.listen(80);
app.get('/:channel/:message', function (req, res) {
//Code to create socket
socket.emit("sent from get", {channel:req.params.channel, message:req.params.message})
});
io.sockets.on('connection', function (socket) {
socket.on('sent from get', function (data) {
socket.broadcast.to(data.channel).emit('channel message', { message: data.message});
});
});
How to I create (and destroy) a socket connection in the app.get block?
(For clarity, I want to use this to send a quick message from a rails server when a particular object is saved, and have a message pushed to each appropriate user.)
io.sockets.in(req.params.channel).emit("channel message", {mes:req.params.message})
That will send a message to all users in the requested channel.
var chat = io.of('/chat').on('connection', function (socket) {
socket.emit('a message', { that: 'only', '/chat': 'will get' });
chat.emit('a message', { everyone: 'in', '/chat': 'will get' }); });
The following example defines a socket that listens on '/chat'

Categories

Resources