I went through several SO threads regarding this. Didn't work anything. But my case is different. In my case, nothing happens. Here is the code:
import amqplib from 'amqplib'
const AMQP_URL = 'amqp://guest:guest#localhost:5672/'
const AMQP_QUEUE_NAME = 'email_queue'
function connectRabbitMQ() {
console.log('Connecting to rabbit mq...')
amqplib.connect(AMQP_URL, async (err: Error, connection: amqplib.Connection) => {
if (err) {
console.log('This log doesn\'t print')
throw err
}
console.log('This log doesn\'t print')
// Listener
const channel1 = await connection.createChannel()
channel1.consume(AMQP_QUEUE_NAME, (msg) => {
if (msg !== null) {
console.log('Recieved:', msg.content.toString());
channel1.ack(msg);
} else {
console.log('Consumer cancelled by server');
}
})
// Sender
const channel2 = await connection.createChannel()
setInterval(() => {
channel2.sendToQueue(AMQP_QUEUE_NAME, Buffer.from('something'))
}, 1000)
})
}
function launchServer() {
console.log('Launching Server...')
console.log('Connecting to MongoDB...')
const MONGODB_URI = process.env.MONGODB_URI?.toString() || ''
mongoose.connect(MONGODB_URI, {}, (err) => {
if (err) {
return console.error('Error connecting to Mongo DB !')
}
console.log('CONNECTED TO MONGO DB')
const port = parseInt(process.env.PORT?.toString() || '3000')
app.listen(port)
console.log('========= SERVER STARTED ========== PORT ' + port)
connectRabbitMQ()
})
}
launchServer()
Neither error nor success occur. The log doesn't get printed. Last log get printed is - Connecting to rabbit mq...
function connectRabbitMQ doesn't seems to be executed.
try appending this on last line of your code
connectRabbitMQ();
Related
I have a tcp socket client connection and server in my app. My main goal is taking data from server and send it to client connection. It works great while my app is running but if i get app to background it just sends one data and sends other datas after opening app again. I tried expo-task-manager but it just sends first data and doesnt sends after it as before. I was using my function inside useEffect in a context component. My function with task manager is below.
const BACKGROUND_CLIENT_TASK = "background-client-task";
TaskManager.defineTask(BACKGROUND_CLIENT_TASK, async () => {
const now = Date.now();
console.log(
`Got background fetch call at date: ${new Date(now).toISOString()}`
);
const mainFunction = async () => {
const server = TcpSocket.createServer(function (socket) {
socket.on("data", (takenData) => {
const jsonStringData = String.fromCharCode(...takenData);
const data = JSON.parse(jsonStringData);
const clientOptions = {
port: 1500,
host: "localhost",
};
const dataToClientArray = [
`DataProcess1${data}`,
`DataProcess2${data}`,
`DataProcess3${data}`,
];
dataToClientArray.forEach((dataToClient, index) => {
setTimeout(() => {
const client = TcpSocket.createConnection(
clientOptions,
() => {
// Write on the socket
client.write(`${dataToClient}`, "hex");
console.log("client started");
console.log(dataToClient);
// Close socket
client.destroy();
}
);
client.on("data", (data) => {
console.log("Received: ", data.toString());
});
client.on("error", (error) => {
console.log("Error: ", error);
});
client.on("close", () => {
console.log("Connection closed");
});
}, 300 * index);
});
});
socket.on("error", (error) => {
console.log("An error ocurred with client socket ", error);
});
socket.on("close", (error) => {
console.log("Closed connection with ", socket.address());
});
}).listen({ port: 1754, host: "0.0.0.0" });
server.on("error", (error) => {
console.log("An error ocurred with the server", error);
});
server.on("close", () => {
console.log("Server closed connection");
});
};
mainFunction();
// Be sure to return the successful result type!
return BackgroundFetch.BackgroundFetchResult.NewData;
});
BTW It doesnt start if i dont add the mainFunction in useEffect
The code that i register my defined Task. (result returns undefined)
async function registerBackgroundFetchAsync() {
return BackgroundFetch.registerTaskAsync(BACKGROUND_CLIENT_TASK, {
minimumInterval: 5, // seconds
stopOnTerminate: false, // android only,
startOnBoot: true, // android only
});
}
const registerFunction = async () => {
const result = await registerBackgroundFetchAsync();
console.log(result);
console.log("resultup");
const status = await BackgroundFetch.getStatusAsync();
const isRegistered = await TaskManager.isTaskRegisteredAsync(
BACKGROUND_CLIENT_TASK
);
setStatus(status);
setIsRegistered(isRegistered);
};
registerFunction();
**Hello, please do you know how can I send message to client via socket when I have error in my SQl query on server side ? **
Server side
io.on('connect', (socket) => {
console.log("User connected: " + socket.id);
socket.on('disconnet', () => {
console.log("disconnected");
})
.post('/addDiel', (req, res) => { //Pridanie dielu do DB
pool.getConnection((err, connection) => {
if(err) throw err
console.log(`Pripojene ako ID ${connection.threadId}`)
const params = req.body;
res.send({
MenoDielures: params.MenoDielu,
DruhDielures: params.DruhDielu,
ProjektNameres: params.ProjektName
})
ProjektNameDB = params.ProjektName.split('.').join("_");
connection.query('INSERT INTO `Skener_db`.`?` (`MenoDielu`, `DruhDielu`, `DatumCas`) VALUES (?, ?, NOW())', [ProjektNameDB, params.MenoDielu, params.DruhDielu],(err, rows)=> {
connection.release()
if(!err) {
res.send(console.log(`Hodnota ${params.MenoDielu} bola pridana.`))
} else {
console.log(err);
if (err.code == ('ER_DUP_ENTRY')) {
//send message to client
}
//res.send({alertMessage: 'Diel už bol oskenovaný. Oskenuj ďaľší.'})
}
})
console.log(req.body)
})
})
})
My client side:
socket.on('connect', () => {
$('#skuska').html("Socket pripojeny");
})
socket.on('receiveDUPmessage', message => {
$('#skuska').html(message);
})
The code here is just for example. I didnt find solution for my problem, so I'm asking here
You have to emit events and socket is locally scoped. io.sockets is not, So you can do it like this on the server-side:
if(!err) {
res.send(console.log(`Hodnota ${params.MenoDielu} bola pridana.`))
} else {
console.log(err);
if (err.code == ('ER_DUP_ENTRY')) {
//send message to client
io.sockets.emit('my error', 'Some error happened');
}
//res.send({alertMessage: 'Diel už bol oskenovaný. Oskenuj ďaľší.'})
}
And on the client-side do this:
socket.on('my error', function (text) {
console.log(text);
});
Here is some sort of posts that may help you:
How to emit error to be possible catch it on error handler on client-side?
How to emit a socket.io response within post request in NodeJS
What is the proper procedure to do ICE restart when using SIP.js? (v0.20.0)
This is what I'm trying:
oniceconnectionstatechange: (event) => {
const newState = sdh.peerConnection.iceConnectionState;
if (newState == 'failed') {
sdh.peerConnection.restartIce();
sdh.peerConnection.createOffer({'iceRestart': true})
.then(function(offer) {
return sdh.peerConnection.setLocalDescription(offer);
});
}
}
It seems to execute without an error, but also no result.
FireFox debug-tool "about:webrtc" shows "ICE restarts: 0", so I guess it didn't even begin restart.
ps: failed state is induced by restarting RTP Engine (Kamailio setup). After RTP Engine restarts there is still audio for about 20 seconds and only when ICE state changes to "failed" audio stops.
Found solution that fixed my problem:
sdh.peerConnectionDelegate = {
oniceconnectionstatechange: (event) => {
const newState = sdh.peerConnection.iceConnectionState;
if (newState === 'disconnected') {
sdh.peerConnection.restartIce();
sdh.peerConnection.createOffer({'iceRestart': true})
.then((offer) => {
sdh.peerConnection.setLocalDescription(offer);
session.sessionDescriptionHandlerModifiersReInvite = [offer];
session.invite()
.then(() => {
session.logger.debug('iceRestart: RE-invite completed');
})
.catch((error) => {
if (error instanceof RequestPendingError) {
session.logger.error('iceRestart: RE-invite is already in progress');
}
throw error;
});
});
}
}
};
I have a react native application where i have two users using the app (customer and restaurant)
So on checkout I connect the customer to websocket on the express server and once the order is placed i send a message to the restaurant which is supposed to be connected to websocket all time.
However, sometimes the restaurant is disconnected somehow, so I am trying to keep the restaurant connected, and if disconnected then reconnect again automatically.
In react native restaurant side implementation i have the following code :
this is useWebSocketLite hook to handle connection, send, receive messages and retry connection to server when closed:
function useWebSocketLite({ socketUrl, retry: defaultRetry = 3, retryInterval = 1000 }) {
const [data, setData] = useState();
const [send, setSend] = useState(() => () => undefined);
const [retry, setRetry] = useState(defaultRetry);
const [readyState, setReadyState] = useState(false);
useEffect(() => {
const ws = new WebSocket(socketUrl);
ws.onopen = () => {
setReadyState(true);
setSend(() => {
return (data) => {
try {
const d = JSON.stringify(data);
ws.send(d);
return true;
} catch (err) {
return false;
}
};
});
ws.onmessage = (event) => {
const msg = formatMessage(event.data);
setData({ message: msg, timestamp: getTimestamp() });
};
};
ws.onclose = () => {
setReadyState(false);
if (retry > 0) {
setTimeout(() => {
setRetry((retry) => retry - 1);
}, retryInterval);
}
};
return () => {
ws.close();
};
}, [retry]);
return { send, data, readyState };
}
So based on this, every-time the connection is closed, the connection will retry again.
Besides, when a restaurant launches the app the following code will be implemented:
const ws = useWebSocketLite({
socketUrl: `wss://${url}/id=${user.user_id}&role=restaurant`
});
This useEffect to establish the connection:
useEffect(() => {
if (ws.readyState === true) {
setConnectionOpen(true);
}
}, [ws.readyState]);
and this useEffect to handle incoming messages
useEffect(() => {
if (ws.data) {
const message = ws.data;
//dispatch...
}
}, [ws.data]);
Express server implementation:
This is the code where i handle socket connections and messages in express server:
var webSockets = {}
function setupWebSocket(server) {
server.on('connection', (socket, req) => {
if (req) {
var clientId = req.url
let regexReplace = /[\[\]/]/g
let regex = /([^=#&]+)=([^?&#]*)/g,
params = {},
match;
while ((match = regex.exec(clientId))) {
params[decodeURIComponent(match[1]).replace(regexReplace, '')] = decodeURIComponent(match[2])
}
if (params.role === 'restaurant') {
webSockets[params.id] = socket
}
}
socket.on('message', data => {
let sData = JSON.parse(JSON.parse(data))
let {id, data} = sData.data
sendToClient(id, 'order', data)
})
socket.on('error', (err) => {
console.log(err)
})
socket.on('close', (code, req) => {
var clientId = req.url
let regexReplace = /[\[\]/]/g
let regex = /([^=#&]+)=([^?&#]*)/g,
params = {},
match;
while ((match = regex.exec(clientId))) {
params[decodeURIComponent(match[1]).replace(regexReplace, '')] = decodeURIComponent(match[2])
}
if (params.role === 'restaurant') {
delete webSockets[clientId]
console.log(`${webSockets[clientId]} disconnected with code ${code} !`);
}
});
});
// sends a message to a specific client
const sendToClient = (clientId, type, data = {}) => {
const payload = { type, data }
const messageToSend = JSON.stringify({ error: false, message: payload })
if (webSockets[clientId]) {
webSockets[clientId].send(messageToSend)
console.log(`${clientId} client notified with this order`)
} else {
console.log(`${clientId} websocket client is not connected.`)
}
}
}
So most of the time I get 13 websocket client is not connected. which means the restaurant has already been deleted from the webSockets object and its connection already closed.
Apologise for long question and hope someone can help me regarding this.
First of all, you should know that this is not a good practice of websockets, where you are forcing the client (the restaurant) to be connected.
Whatever, at the current state of your code, there is an illogical behavior: at the end of the useEffect of your “useWebSocketLite” function, you are closing the socket connection:
return () => {
ws.close();
};
Knowing that the useEffect hook is called twice: after the first render of the component, and then after every change of the dependencies (the “retry” state in your case); Your code can be ridden like so: everytime the “retry” state changes, we will close the socket! So for me that is why you got the client disconnected.
i am getting error in npm mssql 3.0.0 with sqlserver 2012
i am creating single page application where i used restful using express .
there are 4 method which executing the query and returning the data to response.
for each method i am opening the connection and closing the connection.
but when savedquery is calling then connection close error occurs.
each method code is similar to savedquery method (copy pasted code only queries are changed) but they are executing savedquery is not executing
{ [ConnectionError: Connection is closed.]
name: 'ConnectionError',
message: 'Connection is closed.',
code: 'ECONNCLOSED' }
var savedquery=function(req,res){
dbConfig= {
user: 'XXX',
password: 'XXXXXXXXXX',
server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
database: 'DEMO_ODS',
options: {
encrypt: true
}
};
sql.connect(dbConfig).then(function (err) {
var sqlrequest = new sql.Request();
sqlrequest.query("SELECT * from SavedQuery").then(function (recordset) {
sql.close(function (value) {
console.log("connection6 closed");
});
return res.status(200).send(recordset);
}).catch(function (err) {
console.log(err);
});
}).catch(function (err) {
console.log(err);
});
};
}
I know it is an old questionm but this answer is for the others who are facing the same isue. I had the same problem, What I did is, used promises as below.
function getData() {
try {
sqlInstance.connect(setUp)
.then(function () {
// Function to retrieve all the data - Start
new sqlInstance.Request()
.query("select * from Course")
.then(function (dbData) {
if (dbData == null || dbData.length === 0)
return;
console.dir('All the courses');
console.dir(dbData);
})
.catch(function (error) {
console.dir(error);
});
// Function to retrieve all the data - End
// To retrieve specicfic data - Start
var value = 1;
new sqlInstance.Request()
.input("param", sqlInstance.Int, value)
.query("select * from Course where CourseID = #param")
.then(function (dbData) {
if (dbData == null || dbData.length === 0)
return;
console.dir('Course with ID = 1');
console.dir(dbData);
})
.catch(function (error) {
console.dir(error);
});
// To retrieve specicfic data - End
}).catch(function (error) {
console.dir(error);
});
} catch (error) {
console.dir(error);
}
}
This solved my issue. You can find the fix here.
You should remove
options: {
encrypt: true
}
from your dbConfig
I just use promise to handle concurrent request:
const executeQuery = function (res, query, dbName) {
dbConfig = {
user: "********",
password: "********",
server: "*******",
database: dbName
}
sql.connect(dbConfig).then(pool => {
return pool.request().query(query)
}).then(result => {
res.send(result);
}).catch(err => {
res.send(err);
});
}
Hope it's help someone.