I am using socket.io in nodejs for chat system, and I am able to send the message on server in socket.js file in nodejs. But when I emit that message to other users from socket in nodejs. Then this message is not receiving on the client side.
Here is my nodejs code:
var users = [];
const io = require('socket.io')(server, {
pingInterval: 5000,
pingTimeout: 5000
});
io.on('connection', (socket) => {
console.log("User connected: ", socket.id);
socket.on("user_connected", function (id) {
users[id] = socket.id;
io.emit("user_connected", id);
});
socket.on('message', (msg) => {
var socketId = users[msg.friendId];
socket.to(socketId).emit('new_message', msg);
let chat = new ChatData({
user: msg.userId,
friend: msg.friendId,
message: msg.message
});
chat.save().then(() => {
console.log('message saved');
}).catch((err) => {
console.log('error is ', err);
});
});
});
Here is my client side code:
const socket = io("ws://localhost:3000");
socket.on('connect', function() {
socket.emit("user_connected", userId);
});
function sendMessage(message) {
let msg = {
userId: userId,
friendId: friendId,
message: message.trim()
}
// Send to server
socket.emit('message', msg);
}
// Recieve messages
socket.on('new_message', (msg) => {
console.log(msg)
});
Client side socket js library https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.2/socket.io.js
Related
I've had a problem with receiving message from client to server with using React and ExpressJS. After launch sendMessage function on client side I want to send to server my message, but, I don't know why this message is not being received by my server and io.on("message", (message) => { is not launched with his console.log :/
Here is my code
Server side:
index.ts
const server = http.createServer(app);
export const socketIo = socket(server);
socket.ts
export const socket = (httpServer: any) => {
const io = new Server(httpServer, { cors: { origin: "http://localhost:5000" } });
io.on("connection", (socket) => {
console.log("Socket connected!")
socket.emit('connection', null);
});
io.on("message", (message) => {
console.log("NEW MESSAGE: ", message)
})
}
Client side:
App.tsx
const SOCKET_SERVER = "http://127.0.0.1:3000";
export const socket = socketClient(SOCKET_SERVER);
socket.on('connect', () => {
console.log('CONNECTED WITH BACKEND SOCKET')
})
Chat.tsx
const sendMessage = () => {
const message = form.getFieldsValue()["typedMessage"];
socket.emit("message", message);
form.resetFields();
};
thanks for any help!
io.on("connection", (socket) => {
console.log("Socket connected!")
socket.emit('connection', null);
});
io.on("message", (message) => {
console.log("NEW MESSAGE: ", message)
})
The "connection" is triggered on the server listener and provides a connected socket. The socket is then used to receive messages. This means receiving messages must be done on socket, not on the listener io:
io.on("connection", (socket) => {
console.log("Socket connected!")
socket.emit('connection', null);
socket.on("message", (message) => {
console.log("NEW MESSAGE: ", message)
});
});
I'm using socket io in two places in the app:
emiting offers on the main page that everyone can see
emiting chat messages only between two users based on order_id
I was able to set up first use case but not the second. When creating a new message, response status is 500 after hitting the socket part in the controller.
index.js
const serverIO = server.listen(
port,
console.log(`Listening on Port ${port}`)
);
const io = require("./socket").init(serverIO);
io.on("connection", (socket) => {
socket.join("some room");
console.log("cient connected");
});
socket.js
let io;
module.exports = {
init: (httpServer) => {
io = require("socket.io")(httpServer);
return io;
},
getIO: (socket) => {
if (!io) {
throw new Error("Socket.io not initialized!");
}
console.log("socket", socket());
return io;
},
};
chatController.js
const io = require("../socket");
const chatModel = require("./chatModel.js");
exports.createChat = async (req, res) => {
try {
const savedMessage = await chatModel.saveMessage(req.body);
if (!savedMessage) {
return res.status(400).json({
errorMessage: "Something went wrong with your chat request",
});
}
io.getIO().socket.to(req.body.order_id).emit("newMessage", { action: "create", message: savedMessage });
return res.status(200).json(savedMessage);
} catch (error) {
return res.status(500).json({
errorMessage: error,
});
}
};
on the client, I'm listening like this:
Chat.js
useEffect(() => {
const socket = openSocket(baseURL);
socket.on("newMessage", ({ room, data }) => {
console.log("room", room); //not being reached
if (data.action === "create") {
dispatch(addMessage(...data.message));
}
});
}, []);
I tried adding the boilerplate code from documentation but that didn't seem to work.
io.on('connection', socket => {
socket.join('some room');
});
How can I join rooms based on orderId and listen to said room on the client?
Was able to reach a working solution (chat messages are being broadcast only to the intended recipients)but don't know if it's optimal or efficient.
added socket.join in my index.js file
io.on("connection", (socket) => {
socket.on("joinRoom", (room) => {
console.log("joined room");
socket.join(room);
});
console.log("cient connected");
});
modified my controller
io.getIO().to(req.body.order_id).emit("newMessage", {
action: "create",
message: savedMessage,
});
And on the front end, on mount, I'm joining a room and listening for newMessage from server.
useEffect(() => {
const socket = openSocket(baseURL);
socket.emit("joinRoom", orderId);
socket.on("newMessage", (data) => {
console.log("data", data);
if (data.action === "create") {
dispatch(addMessage(...data.message));
}
});
}, []);
im building a chat app using express and react and socket.io, and everything works, except that when I emit message from my server, it doesn't catch it in the client. Why is that? My code is:
index.js (server)
const io = require('socket.io')(server);
io.on('connection', socket => {
socket.on('join-room', data => {
console.log(`Joining room ${data.room}`);
socket.join(data.room);
});
socket.on('leave-room', data => {
console.log(`Leaving room room ${data.room}`);
socket.leave(data.room);
});
socket.on('new-message', data => {
console.log(`Sending message to room ${data.room}`);
socket.to(data.room).emit('new-message', data.message);
});
});
JoinRoom.js (react)
useEffect(() => {
socket.on('new-message', data => {
console.log('getting new message');
setMessages([...messages, data]);
});
}, [messages]);
useEffect(() => {
socket.emit('join-room', { room: id });
async function fetchData() {
const response = await req.get('/api/room/' + id);
setRoom(response.data);
const _messages = await req.get('/api/messages/' + id);
setMessages(_messages.data.docs);
}
fetchData();
}, [id]);
const send = e => {
e.preventDefault();
socket.emit('new-message', {
room: id,
message: newMessage
});
const data = {
message: newMessage,
user: 'Mikolaj',
roomId: id
};
req.post('/api/messages/send', data);
setNewMessage('');
};
I am sending data to all clients but it only APPEND on sender's Message body. In this case, real-time data is only working on sender only but i need to work on every connected users.
After reading the documentation it says, BROADCASTING could be the solution but its not showing for sender(Which means OK) But that also not showing for other connected receivers.
Custom.js
var socket = io.connect("http://localhost:3000/");
$.ajax({
url: 'sent',
type: 'POST',
data: {
msg: 'Some message'
},
dataType: "json",
success: function (data) {
if (data.message) {
socket.emit('send', {
msg: data.msgResult
});
socket.on('msgResult', result => {
$(".msgDiv").append(result);
});
}
}
});
App.js
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
io.on('connection', (socket) => {
console.log('Socket.io connected...');
socket.on('send', (data) => {
socket.emit('msgResult', data.msg);
});
socket.on('disconnect', () => {
console.log("A socket Discounted ..");
});
});
I want to append data to all connected users including sender too.
If you want to send message to all connected sockets you can use
io.sockets.emit('msgResult', 'data');
and if you want to send message to all connected sockets except sender, use
socket.broadcast.emit('msgResult', 'data');
your index.js for socket server should have
//webServerPort= localhost:3000
const server = http.createServer(app);
let constAppServer = server.listen(webServerPort);
let io = socketServer(constAppServer);
app.set('socket',io);
io.on('connection', function (socket) {
console.log('connection opened');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('udagent',function(msg){
console.log('message: ' + msg);
});
});
this is your event.js when you want to send a event to frontend
const testFunction =(req,res)=> {
let io = req.app.get('socket');
io.emit('dashboard_event', { "totalMin": data });
}
i had api for broadcasting my admin notifications to all the agents under me by creating and passing this api
const broadCastUpdates =(req,res)=> {
const {message} = req.body
let io = req.app.get('socket');
io.broadcast.emit('broadCastToAgents', { 'data':message });
}
Finally i found my answer. it was a simple mistake which takes a lot of time.
custom.js
var socket = io.connect("http://localhost:3000/");
$.ajax({
url: 'sent',
type: 'POST',
data: {
msg: 'Some message'
},
dataType: "json",
success: function (data) {
if (data.message) {
socket.emit('send', {
msg: data.msgResult
});
}
}
});
socket.on('msgResult', result => {
$(".msgDiv").append(result);
});
App.js
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
io.on('connection', (socket) => {
console.log('Socket.io connected...');
socket.on('send', (data) => {
socket.emit('msgResult', data.msg);
});
socket.on('disconnect', () => {
console.log("A socket Discounted ..");
});
});
i just plug out my msgResult from ajax submission. That's it.
I have the following node-xmpp server. At this server I connect 2 clients and send messages one to each other.In console I want to see received message but I see the message that I send.Any ideas?
Here is the code :
server:
'use strict'
var xmpp = require('../index')
, server = null
, Client = require('node-xmpp-client')
var startServer = function(done) {
// Sets up the server.
server = new xmpp.C2S.TCPServer({
port: 5222,
domain: 'localhost'
})
// On connection event. When a client connects.
server.on('connection', function(client) {
// That's the way you add mods to a given server.
// Allows the developer to register the jid against anything they want
client.on('register', function(opts, cb) {
console.log('REGISTER')
cb(true)
})
// Allows the developer to authenticate users against anything they want.
client.on('authenticate', function(opts, cb) {
console.log('server:', opts.username, opts.password, 'AUTHENTICATING')
if (opts.password === 'secret') {
console.log('server:', opts.username, 'AUTH OK')
cb(null, opts)
}
else {
console.log('server:', opts.username, 'AUTH FAIL')
cb(false)
}
})
client.on('online', function() {
console.log('server:', client.jid.local, 'ONLINE')
})
// Stanza handling
client.on('stanza', function(stanza) {
console.log('server:', client.jid.local, 'stanza', stanza.toString())
var from = stanza.attrs.from
stanza.attrs.from = stanza.attrs.to
stanza.attrs.to = from
client.send(stanza)
//console.log('Stanza sent is :'+stanza);
})
// On Disconnect event. When a client disconnects
client.on('disconnect', function() {
console.log('server:', client.jid.local, 'DISCONNECT')
})
})
server.on('listening', done)
}
startServer(function() {
})
Code for clients:
Client1:
var xmpp = require('node-xmpp');
// On Connect event. When a client connects.
client = new xmpp.Client({jid: 'admin#localhost', password: 'secret'});
client.addListener("authenticate", function(opts, cb) {
console.log("AUTH" + opts.jid + " -> " +opts.password);
cb(null, opts);
});
client.addListener('error', function(err) {
console.log(err.toString());
});
client.addListener('online', function() {
console.log("online");
var stanza1 = new xmpp.Element('message', { to: 'admin6#localhost', type: 'chat', 'xml:lang': 'ko' }).c('body').t('aaaaaMessage from admin');
//setInterval(sender,1000);
client.send(stanza1);
});
//client.on("stanza", function(stanza) {
//console.log("STANZA" + stanza);
// console.log('S-a primit ceva: '+stanza);
//});
client.on('stanza',function(message){
console.log('AAAA '+message);
})
client.addListener("disconnect", function(client) {
console.log("DISCONNECT");
});
CLient2 :
var xmpp = require('node-xmpp');
// On Connect event. When a client connects.
client = new xmpp.Client({jid: 'admin6#localhost', password: 'secret'});
client.addListener("authenticate", function(opts, cb) {
console.log("AUTH" + opts.jid + " -> " +opts.password);
cb(null, opts);
});
client.addListener('error', function(err) {
console.log(err.toString());
});
client.addListener('online', function() {
console.log("online");
var stanza = new xmpp.Element('message', { to: 'admin#localhost', type: 'chat', 'xml:lang': 'ko' }).c('body').t('aaaaaMessage from admin6');
//setInterval(sender,1000);
client.send(stanza);
});
client.on("stanza", function(stanza) {
console.log("STANZA" + stanza);
//console.log('S-a primit ceva: '+stanza);
});
//client.addListener('stanza',function(message){
// console.log('AAAA '+message);
//})
client.addListener("disconnect", function(client) {
console.log("DISCONNECT");
});