Electron + React && node JS Vending Machine using TCP/IP
Clone the repo and install dependencies:
git clone --branch master https://github.com/MinWook6457/Vending-Machine-Using-TCPIP.git
cd server
npm install
cd ..
cd vending
npm install
Having issues installing? Contact me Email
Start the app in the dev
environment:
cd server
npm start or pm2 start (set PM2 on this Project)
cd ..
cd vending
npm start
To package apps for the local platform:
npm run package
First
Open IPCRenderer Channel in preload
contextBridge.exposeInMainWorld('ipcRenderer', {
on: (channel, func) => {
ipcRenderer.on(channel, (event, ...args) => func(event, ...args));
},
invoke: (channel, ...args) => {
return ipcRenderer.invoke(channel, ...args);
},
removeAllListeners: (channel) => {
ipcRenderer.removeAllListeners(channel);
},
send : (channel, ...args) => {
ipcRenderer.send(channel, ...args);
}
});
window.ipcRenderer.channel
Example ...
await window.ipcRenderer.invoke('channel', {});
use handle function and get response
Example ...
ipcMain.handle('getBuy', async (event, payload) => {
const { beverage, stock , price, inputCoin} = payload;
console.log(beverage, stock, price, inputCoin);
try {
const response = await buyDrink(beverage, stock, price, inputCoin);
return response;
} catch (error) {
console.error('Error in getBuy handler:', error);
return { success: false, message: error.message };
}
});
use Promise and using socket write data to server
Example ...
function buyDrink(beverage, stock, price, inputCoin) {
return new Promise((resolve, reject) => {
const payload = JSON.stringify({ beverage, stock, price, inputCoin });
socket.write(`buy${payload}`);
socket.once('data', (data) => {
try {
const response = JSON.parse(data.toString());
resolve(response);
} catch (error) {
reject(new Error('Failed to parse server response'));
}
});
socket.once('error', (err) => {
reject(new Error('socket1 error: ' + err.message));
});
});
}
Example ...
if (data.startsWith('input')) {
const payload = data.substring(5);
.
.
.
Example ...
if (data.startsWith('makeUpCoin')) {
try {
const coinData = await Coin.findAll({
attributes: ['unit', 'price', 'change'],
});
const refreshData = JSON.stringify(coinData);
socket.write(JSON.stringify({success: true, message: '전체 화폐 데이터 전달', refreshData}));
} catch (err) {
socket.write(JSON.stringify({success: false, message: '화폐 데이터 전달 중 에러'}));
}
}
MIT ©