socket connected but not emit the message - javascript

Client-Side:
the socket used in website, initially connected and socket id is generated, but when try to emit the message, unable to emit from client to server-side.
<script>
const socket = io("http://localhost:8080");
socket.on("connection",() => {
})
const socketTrigger = () => {
console.log("message")
socket.emit("message", "testing data")
}
</script>
Server Side:
io.on("connection", socket => {
socket.on("message", (data) => {
console.log("message", data)
})
socket.on("startBidding", isAdminPage => {
socket.broadcast.emit("startBiddingArray", isAdminPage);
socket.on("disconnect", () => {
console.log("Client disconnected");
});
});
})

You just assign a variable with an anonymous function, but you don't call it like: socketTrigger(); at the end of the script.

Related

How to pass data from net.Socket.on to an outside variable or return it

I'm working with net in node.js and I'm sending packet to a server and listening to the response, but I can't manage to return it. Here's my code:
function packetsend (sockeT, packeT) {
var resp = null;
if(sockeT) {
sockeT.write(packeT);
sockeT.on('data', (data) => {
resp = data.toString()
})
}
return resp;
}
const socket = new net.Socket();
socket.connect({host: server, port: port}, function() {
console.log('Connected');
var packetRecv = packetsend(socket, 'some packet');
if (packetRecv === 'some') {
console.log("ok");
}
})
I don't understand why packetsend() function is not returning the updated resp variable, and sends undefined object instead. When I do console.log(data) inside the sockeT.on() I see that it receives data.
Try transforming your packetsend() function in an async function. Maybe it's not returning the resp because you return it before the event 'data' is invoked.
This is just an example of a possible implementation:
function packetsend (sockeT, packeT) {
return new Promise((resolve, reject) => {
if (sockeT) {
sockeT.write(packeT);
sockeT.on('data', (data) => {
resolve(data.toString());
});
//WARNING: I don't know this 'socketT' object, don't know if there is an 'error' event.
//but it's recommended to handle errors. This is just an example.
sockeT.on('error', (error) => {
reject(error);
});
}
else{
reject('Missing sockeT');
}
});
}
const socket = new net.Socket();
socket.connect({ host: server, port: port }, function () {
console.log('Connected');
packetsend(socket, 'some packet').then(packetRecv => {
console.log('Received data => '+ packetRecv);
if (packetRecv === 'some') {
console.log("ok");
}
}).catch(error => console.log(error));
})
Update: you can also use the async/await
const socket = new net.Socket();
socket.connect({ host: server, port: port }, async function () {
try {
console.log('Connected');
let packetRecv = await packetsend(socket, 'some packet');
console.log('Received data => '+ packetRecv);
if (packetRecv === 'some') {
console.log("ok");
}
}
catch (error) {
console.log(error);
}
});
Tips:
"promise" documentation
"eventEmitter" documentation
"async/await" documentation

Socket.IO triggering request every second

I wonder how to stop socketio to trigger request every second. Here is my back and front end code:
io.on('connection', (socket) => {
console.log(`a user connected`)
socket.on('join', (data) => {
socket.broadcast.emit(
'player action',
`${data.name} has join the table`
)
console.log('user', `${data.name} has joined `)
console.log('data player: ', data)
})
socket.on('quit', (data) => {
socket.broadcast.emit('player action', `${data.name} has left`)
console.log(`user ${data.name} has left`)
})
socket.on('disconnect', () => {
console.log('a user quit')
})
})
on the client side there is only that:
const socket = io()

Simple peer and socket.io keeps sending back and forth requests 100s of times. Unable to establish signal connections

I am trying to establish a connection between the two different users on the server. Every time a users joins the room he gets the info about the socket.ids of other users in the room. What they try and do is the new user creates an initiator peer and sends a signal . Which the other peer accepts for some reason they both keep sending each other back and forth requests and no one access each other requests this is what is happening.
A picture of the backend console
createPeer = (userToSignal, callerId, stream) => {
console.log('create peer called', userToSignal);
const peer = new Peer({
initiator: true,
trickle: false,
stream: stream
})
peer.on('signal', signal => {
console.log('sending a signal to server')
this.socket.emit('sending signal', {
'userToSignal': userToSignal,
'callerId': callerId,
'signal': signal
});
});
return peer;
}
addPeer = (incomingSignal, callerId, stream) => {
console.log('Add peer called', callerId);
const peer = new Peer({
initiator: false,
trickle: false,
stream: stream
});
peer.signal(JSON.stringify(incomingSignal));
peer.on('signal', signal =>{
console.log('returning a signal to : ', callerId)
this.socket.emit('returning signal', {
'signal': signal,
'callerId': callerId
});
});
return peer;
}
joinCall = () => {
navigator.mediaDevices.getUserMedia({ video: false, audio: true }).then(stream => {
console.log(this.socket.id);
this.socket.emit('join call', this.state.id, this.state.userName);
console.log('Join Call Called')
this.socket.on('all users', (usersInThisRoom) => {
console.log('all users ', usersInThisRoom);
const peers = [];
usersInThisRoom.forEach(user => {
console.log('for each called')
const peer = this.createPeer(user['id'], this.socket.id, stream);
peers.push({
'peerId' : user['id'],
'peer': peer
})
});
this.peersRefs = peers;
this.setState({peersRefs : this.peersRefs});
});
this.socket.on('user joined', payload => {
console.log('new user has joined', payload['callerId']);
const peer = this.addPeer(payload['signal'], payload['callerId'], stream);
this.peersRefs.push({
'peerId': payload['callerId'],
'peer': peer
})
this.setState({'peersRefs': this.peersRefs});
});
this.socket.on('receiving returned signal', payload => {
console.log('returned signal recieved ', payload.id)
const peerToSignal = this.peersRefs.find(peer => peer['peerId'] === payload.id)
peerToSignal['peer'].signal(JSON.stringify(payload.signal));
});
});
console.log('joining')
}
This is my front end code ^^
// Changes start
socket.on('join call', (roomId, name) => {
console.log('New User ', name)
SessionModel.findById(roomId, (err, session, callback) => {
if (err) throw err;
let users = session.usersInCall;
if (users.length === 10) {
return;
}
let userObject = { 'id' : socket.id, 'name' : name};
users.push(userObject);
SessionModel.findOneAndUpdate({_id: roomId}, {usersInCall: users}, {
new: true
},
(err) => {
if (err) throw err
});
const usersInThisRoom = users.filter(user => {
return user['id'] !== socket.id;
});
console.log(usersInThisRoom);
socket.emit("all users", usersInThisRoom);
})
})
socket.on('sending signal', payload => {
console.log('Sending Signal',payload['userToSignal'] );
io.to(payload['userToSignal']).emit('user joined', {
'signal': payload['signal'],
'callerId': payload['callerId']
});
})
socket.on('returning signal', payload => {
console.log('forwarding signal ',payload['callerId'])
io.to(payload['callerId']).emit('receiving returned signal', {
'signal' : payload['signal'],
'id': socket.id
});
})
This is my back end code ^^^
Try putting all ur socketio listners inside useEffect
Looks like you have created an infinite loop. Form the backend logs is
"forwarding signal ......" should have only be printed once. As the client socket is emitting the event returning signal twice.
Adding the client console logs would have helped in debugging.

node mqtt server not propagating publishings

in this sample project i am trying to subscribe to a channel and publish into it.
However i never get back the message sent to the broker.
This is the server:
const mqttServer = require("mqtt-server");
const servers = mqttServer(
{
mqtt: "tcp://localhost:1883",
mqttws: "ws://localhost:1884",
},
{
emitEvents: true, // default
},
client => {
console.log("client connected!");
// console.log(client)
client.connack({
returnCode: 0,
});
client.on("data", data => {
console.log("got data: ");
console.log(data);
client.puback({messageId:data.packetId, ...data})
});
client.on("error", err => {
console.log(err);
});
},
);
servers.listen(_ => {
console.log("listening!");
});
servers.close(_ => {
console.log("close!");
});
And this is the client:
const mqtt = require("mqtt");
const client = mqtt.connect("mqtt://localhost:1883");
client.on("connect", ack => {
console.log("connected!");
// console.log(ack);
client.subscribe("/test", err => {
console.log(err);
});
client.on("message", (topic, message) => {
console.log(topic);
// message is Buffer
console.log(message.toString());
});
setInterval(_ => {
client.publish("/test", "Hello mqtt");
}, 3000);
});
client.on("error", err => {
console.log(err);
});
Any thoughts on what am i missing?
Turns out that using aedes broker the scenario on the sample project worked just fine!

Socket.io Rooms

In below program, cashier.js call join_session/room in server, every time it emits cart_items, then the server will emit it to all client in that specific room. So the question is this the right way to do it, do i really need to call join_session/room in my cashier.js every time it emits data?
server.js
let nsp = io.of('namespace_name');
let session;
nsp.on('connection', function (socket) {
socket.on('join_session', function (client_ip) {
session = client_ip;
socket.join(session);
console.log('New session (' + session + ')');
socket.on('cart_items', function (data) {
console.log(session);
console.log(data);
nsp.to(session).emit("cart_items", data);
});
});
});
cashier.js
socket.on('connect', function () {
socket.emit('join_session', session);
socket.emit('cart_items', { name: item.name, price: item.price });
});
customer.js
socket.on('connect', function () {
socket.emit('join_session', session);
socket.on('cart_items', function (data) {
console.log(data);
});
});
FYI when i try to do this in my cashier.js
socket.on('connect', function () {
socket.emit('join_session', session);
});
//on button click
socket.emit('cart_items', { name: item.name, price: item.price });
There were times that client 1 sends data to client 2 and vice versa.

Categories

Resources