I was following the example this blog and the question arose me after implementing
https://github.com/DanialK/ReactJS-Realtime-Chat
Summarizing, before send a message via websocket the state of messages is updated.
And when server receives that message, they send a broadcast to all clients, indluding myself.
Thereat, client updates the state with this same message
Why this message does not appear 2 times?
I don't want that message appear 2 times, but I want to know why it happens
Client code:
socket.on('send:message', this.messageRecieve);
...
handleMessageSubmit : function(message){
Messages.push(message);
this.setState({ messages : Messages });
socket.emit('send:message', message);
},
messageRecieve: function(message){
Messages.push(message);
this.setState({ messages : Messages });
},
Server code:
socket.on('send:message', function (data) {
socket.broadcast.emit('send:message', {
user: name,
text: data.text
});
});
The server does not send the message to the connected user.
As per the socket.io documentation, this API sends to all but the owner of the socket:
socket.broadcast.emit('send:message')
https://github.com/DanialK/ReactJS-Realtime-Chat/blob/master/routes/socket.js
Related
After the client emits a message to the server, I'm trying to emit that message to every other client in the room, however the original client who sent the message also receives the emit... This seems to go completely against all documentation I've read. My code is as follows:
socket.on('slots', (slots) => {
console.log(socket.id);
const [thisRoom] = socket.rooms;
console.log(thisRoom);
socket.to(thisRoom).emit('slots', slots);
});
I'm using socket.io 4.5.3.
Many thanks.
Check this answer Send a response to all clients except the sender
// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");
Please note that broadcasting is a server-only feature.
Therefore you need to configure this in the server.
io.on('connection', (socket) => {
socket.on('chat message', msg => {
socket.broadcast.emit('chat message', msg);
});
});
So I have set up a socket connection for a chat app. Under normal circumstances where both the sender and receiver are connected to the internet, the message sent between either of them passing through my NodeJS server reach's them. But if one of them is offline and a new message is sent to them, the server will send it to the user but, since the user is offline, won't accept them at that point in time. But once the user gets back online, he should be able to accept that message. How do I make this work?
Nodejs server code
io.on("connection", (socket) => {
console.log("Connected to socket io");
socket.on('setupConnection',(userData)=>{
socket.join(userData.id);
});
socket.on("newMessage", (chatData) => {
const { message,to } = chatData;
socket.in(to).emit("newMessage", { msg: message });
});
})
I am trying to use websocket.io with nodejs and angular. I am trying to build a one-to-one chat application. Here is snippets of my code:
server.js
app.io.on('connection', function(socket){
console.info(`Client connected [id=${socket.id}]`);
socket.on('disconnect', function(){
console.info(`Client gone [id=${socket.id}]`);
});
});
sendmessage.js
router.post("/auth/sendMessage", function(req, res) {
//rest api to handle send message
//mongodb insert
app.io.emit('new-message', { message: message});
}
Angular Client
this.socket.on("new-message", function(data) {
if (
data.message.conversationId === self.conversationId &&
data.message.sender === "customer"
) {
self.messages.push(data.message);
setTimeout(function() {
self.messagesDiv.nativeElement.scrollTop =
self.messagesDiv.nativeElement.scrollHeight;
}, 100);
}
});
Now, the problem that I am facing is new-message will send message to all the listeners. Although, I am handling the logic on the client side, to only show the message if it is sent by specific conversationId, this should be handled at the server end only due to security issues.
So, I want to be able to send to specific users only. I think this can somehow be done using socket.id which would be unique for each connection. But how can I pass this socket.id from client to server, so that server knows on which client it needs to send the data?
There are two things here, app.io and socket. In the first snippet, you use app.io.on('connection', function(socket){. This socket is the new connection. You can store this socket object somewhere in the database or in memory.
Now, app.io.emit will send the message to all the clients, while this socket that you stored somewhere will send the message to that particular client/user on socket.emit.
In short, you need to do
router.post("/auth/sendMessage", function(req, res) {
//rest api to handle send message
//mongodb insert
socket.emit('new-message', { message: message});
}
Here is a small tic-tac-toe game I made using sockets. It will give you more insight on how to use sockets. This is not perfect but you will still understand how to use sockets.
tl;dr save socket from app.io.on('connection'... and use socket.emit to send messages to that particular client.
I have an electron app where different clients communicate with a server over a Network using node-ipc.
As long as the client connects to the server first it is no problem to answer that specific client. According to the docs I have on the Server:
NodeIpc.serveNet(
function () {
NodeIpc.server.on(
'Client.message',
function (data, socket) {
NodeIpc.log('got a message from', (data.id), (data.message));
NodeIpc.server.emit(
socket,
'ServerData',
{
message: 'have some initial cofiguration data'
}
);
);
NodeIpc.server.start();
}
and on my Client:
NodeIPC.connectToNet(
'world',
function(){
NodeIPC.of.world.on(
'connect',
function(){
NodeIPC.log('## connected to world ##', NodeIPC.config.delay);
NodeIPC.of.world.emit(
'Client.message',
{
id : UniqueClientID,
message : 'Some information about myself'
}
);
});
});
That works great, but I cannot figure out how to push some additional information to a specific client some time Later. Trying
NodeIpc.server.of['UniqueClientID'].emit(
'additional Data',
{
message: 'some more configuration'
}
)
});
and
NodeIpc.server.emit(
UniqueClientID,
'additional Data',
{
message: 'some more configuration'
});
do not work.
Does anyone know how to send a message to a given client? (of course there is always the possibility to broadcast that message and let the client decide if it's for him, but I would prefer to talk to the directly)
I have setup a node js server with Mosca running on it. Clients are able to connect to the Mosca server and publish a message. I need to the send an acknowledgment in the form of a message(subscribed to some topic) back to the client.
The below code sends multiple messages continuously once the message is published by the client. Am I missing anything?
var settings = {
port: 1882,
backend: ascoltatore
};
var message = {
topic: 'crofters',
payload: 'OK', // or a Buffer
qos: 2
};
var server = new mosca.Server(settings);
server.on('clientConnected', function(client) {
console.log('client connected', client.id);
});
// fired when a message is received
server.on('published', function(packet, client ) {
var packet_payload = packet.payload;
packet_payload = packet_payload.toString();
console.log('Published', packet_payload);
server.publish(message, function() {
console.log('done!');
});
});
server.on('ready', setup);
function setup() {
console.log('Mosca server is up and running');
}
The event listener server.on('published', function(packet, client){...} listens to every publishing events, including the server's.
What is happening is that when you use server.publish(message, function(){...}) inside that listener it triggers another published event, which is immediately caught by the listener.
It never stops publishing because it never stops catching its own events.
I have been facing similar issues. If you notice, Mosca has only QoS 0 and Qos 1
So I suppose the broker tries to send the same message more than once "at least once" until it receives some acknowledgement from a client. Check this document out