when I connect I get the initial data as if I opened the telnet manually from the CMD, but I'm trying to send a command and it doesn't seem to be working as it's not logging the data. I looked everywhere and I'm not sure what to do.
Here is the code I used
const conn = new net.Socket();
conn.connect({port: 587, host: mxOrDomain}, () => {
conn.setEncoding('utf8');
conn.on('data', (data) => {
const message = data.toString();
console.log(message);
});
conn.on('error', (data) => {
console.log('error : ', data);
});
conn.on('drain', () => {
console.log('drained');
});
conn.on('end', () => {
console.log('Ended');
});
setTimeout(() => {
conn.write('HELO blahbalh.com\\r\\n', 'utf8');
}, 2000);
});
Also, is there a reason why telnet {domain} 587 works in CMD and not when using cp.exec() or .spawn() ?
Turns out you have to end your write string with \r\n but my IDE put \\r\\n by default.
Related
I have this code in my service worker:
messaging.onBackgroundMessage(function (payload) {
console.log("onBackgroundMessage email and contact_link:");
console.log(payload.data.email,payload.data.contact_link);
self.clients.matchAll().then(clients => {
clients.forEach(client => client.postMessage({
msg: "This is a message from the SW",
email: payload.data.email,
contact_link: payload.data.contact_link
}));
})
});
I have this code on the client:
navigator.serviceWorker.addEventListener('message', payload => {
console.log("Message from ServiceWorker");
console.log(payload.data.msg, payload.data.email, payload.data.contact_link);
});
I get the data properly on the console from the service worker, however the client's console says all the data is undefined.
Why is that, what am I doing wrong?
I still do not know why it does not work, but I used this code on the server:
const channel = new BroadcastChannel('sw-messages');
channel.postMessage(payload.data);
And this code on the client instead:
const channel = new BroadcastChannel('sw-messages');
channel.addEventListener('message', event => {
console.log('Received:', event.data);
});
It works well.
I have an Express server waiting for my website to do something. When my site does something, a shell script should be called on the Express server. The problem is: The shell script is only run after the "confirm window" has been accepted or denied. I want the fetch to happen as soon as possible. I wouldn't even need to get anything from the Express server, I just want to signal Express to run the shell script as soon as possible.
I have this code on the website:
messaging.onMessage(function (payload){
fetch("http://localhost:9000/testAPI")
.then(res => res.text())
.then(res => console.log("something:" + res));
var r = confirm(callingname + " is calling.");
if (r == true) {
window.open(payload.data.contact_link, "_self");
} else {
console.log("didn't open");
}
});
I have this code on the backend:
var express = require("express");
var router = express.Router();
router.get("/", function(req,res,next){
const { exec } = require('child_process');
exec('bash hi.sh',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
res.send("API is working");
});
module.exports = router;
confirm() is blocking, and you only have a single thread. This means confirm() will stop the world for your application, preventing fetch() from doing anything.
As the simplest possible fix, you can try delaying the moment when confirm() is invoked. This would allow fetch() to get the request out.
messaging.onMessage(function (payload) {
fetch("http://localhost:9000/testAPI")
.then(res => res.text())
.then(text => console.log("something:" + text));
setTimeout(function () {
if (confirm(`${callingname} is calling.`)) {
window.open(payload.data.contact_link, "_self");
} else {
console.log("didnt open");
}
}, 50);
});
Other options would be to put confirm() into one of the .then() callbacks of fetch, or to use a non-blocking alternative to confirm(), as suggested in the comments.
I'm having a problem with socket.io at the moment I try to send a second time from the server to the client
here is the server code with express and socket.io
io.on('connection', async function (socket) {
let socketId = socket.id;
const mta = new Client("20.64.24.144", 22005, "*", "*");
mta.resources.evokestats.getPlayerCount()
.then((result) => {
console.log("result", result);
socket.emit("players-start", { players: result })
})
.catch((err) => {
console.error(`Ooops! Something went wrong ${err}`);
});
app.post('/player_connect', async function (req, res) {
let ip = req.body[0];
let player = await players.findOne({ ip: ip })
if (player) {
await socket.emit("players", { players: req.body[1] })
} else {
try {
player = await players.create({ ip: ip, name: req.body[2] })
await socket.emit("players", { players: req.body[1] })
await socket.emit("last_24_players", { players: 1 });
} catch (error) {
console.log("error", error)
}
}
res.send("connected")
});
});
and here is my client with reactjs and socket.io
useEffect(() => {
getStats();
}, [])
async function getStats(params) {
socket.on("players-start", function (data) {
setNowPlayers(data.players)
});
socket.on("players", function (data) {
console.log("players", data)
setNowPlayers(data.players)
});});
And in my client using react, in useEffect I listen to the "players-start" and the "players" that was emit.
players-start: It is for every first time that I enter my client he only calls once, to bring all players connected
players: Every time someone connects to the game server, a post call is made to my server where I use the express with socket, in the url '/player_connect' and then immediately emit
The problem: whenever I issue an issue on 'players-start' and then immediately enter the game server that calls the url '/player_connect' it is not triggering the issue of 'players' or at least the client is not receiving.
Test I've done:
My first attempt was to stick everything to the listener "players" but it still doesn’t work
I really appreciate everyone's help.
I am trying to build a web app to stream music. I use MongoDB to store the audio, a Node API to connect to the database and a Vuejs frontend. Below is the endpoint which streams the music, based on this article: https://medium.com/#richard534/uploading-streaming-audio-using-nodejs-express-mongodb-gridfs-b031a0bcb20f
trackRoute.get('/:trackID', (req, res) => {
try {
var trackID = new ObjectID(req.params.trackID);
} catch (err) {
return res.status(400).json({ message: "Invalid trackID in URL parameter. Must be a single String of 12 bytes or a string of 24 hex characters" });
}
res.set('content-type', 'audio/mp3');
res.set('accept-ranges', 'bytes');
let bucket = new mongodb.GridFSBucket(db, {
bucketName: 'tracks'
});
let downloadStream = bucket.openDownloadStream(trackID);
downloadStream.on('data', (chunk) => {
res.write(chunk);
});
downloadStream.on('error', () => {
res.sendStatus(404);
});
downloadStream.on('end', () => {
res.end();
});
});
I tested it with Postman and it works there. I am trying to read the stream in my Vuejs application. I'm just not sure how to do it. I tried the following to test it:
const url = 'http://localhost:4343/api/track/6061c90b2658b9001e65311d';
http.get(url, function (res) {
res.on('data', function (buf) {
console.log(buf);
});
res.on('end', function () {
console.log('ended');
});
})
This does not work however. How should I go about reading it in the frontend?
I'm currently experimenting with Kurento Media Server to rebuild the One2Many example with NodeJS, Socket.io and React but I cannot seem to establish a conenction between the publisher and KMS.
The SDP offer is transmitted to KMS and the answer is transmitted to the client. Every ICECandidates from KMS and the client are transmitted too. The video feedback is showing on the app but nothing is sent to the server and there is no errors. Here's is the chrome://webrtc-internals for my app.
The example app is perfectly working with the same Kurento server, I checked every line and I'm doing the same calls on the backend and on the frontend. Here's the chrome://webrtc-internals for the example app.
For reference, here's the code I'm using on the backend (the errors checking have been removed for this example but nothing is raising an error when I'm using it):
io.on('connect', (socket) => {
const socketInfo = {};
socketInfo.webrtcEndpointCreation = new Promise((resolve, reject) => {
socketInfo.webrtcEndpointCreationResolve = resolve;
socketInfo.webrtcEndpointCreationReject = reject;
});
socket.on('broadcast', (infos, callback) => {
kms.client.create('MediaPipeline', (mediaPipelineError, pipeline) => {
mediaPipeline = pipeline;
mediaPipeline.create('WebRtcEndpoint', (webRtcEndpointError, webRtcEndpoint) => {
socketInfo.webRtcEndpoint = webRtcEndpoint;
presenterWebRtc = webRtcEndpoint;
socketInfo.webrtcEndpointCreationResolve();
webRtcEndpoint.on('OnIceCandidate', (event) => {
socket.emit('iceCandidate',
new kms.lib.register.complexTypes.IceCandidate(event.candidate));
});
webRtcEndpoint.processOffer(infos.sdpOffer, (error, sdpAnswer) => {
callback(null, sdpAnswer);
});
webRtcEndpoint.gatherCandidates();
});
});
});
socket.on('iceCandidate', (candidate) => {
socketInfo.webrtcEndpointCreation.then(() => {
socketInfo.webRtcEndpoint.addIceCandidate(candidate);
});
});
});
And this is the client code:
const options = {
localVideo: document.getElementById('video'),
onicecandidate: (candidate) => {
global.socket.emit('iceCandidate', candidate);
}
};
this.kurentoSocket = new WebRtcPeer.WebRtcPeerSendonly(options, (error) => {
this.kurentoSocket.generateOffer((err, sdpOffer) => {
global.socket.on('iceCandidate', (iceCandidate) => {
this.kurentoSocket.addIceCandidate(iceCandidate);
});
global.socket.emit('broadcast', { sdpOffer }, (broadcastErr, sdpAnswer) => {
this.kurentoSocket.processAnswer(sdpAnswer);
});
});
});
I finally found the problem, it was a Backend issue.
I need to create a IceCandidate object with new kms.lib.register.complexTypes.IceCandidate(candidate) from the message sent by the client before adding it. Because of the way promises works, the error was ignored.