web-protocols/backend/index.js

77 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2024-12-18 15:19:55 +03:00
// Import Express
const express = require('express');
const cors = require('cors');
const http = require('http');
const path = require('path');
const multer = require('multer');
const { Server } = require('socket.io');
const app = express();
let corsOptions = {
2024-12-18 15:37:00 +03:00
origin : ['*'],
2024-12-18 15:19:55 +03:00
}
2024-12-18 15:37:00 +03:00
app.use(cors())
2024-12-18 15:19:55 +03:00
// Configure Multer for file uploads
const upload = multer({
dest: 'uploads/' // Destination folder for uploaded files
});
// Define a route
app.get('/', (req, res) => {
res.send('Welcome to the Express.js');
});
// Start the server
app.listen(7777, () => {
console.log('HTTP is running on port 7777');
});
app.post('/http', upload.single('file'), (req, res) => {
try {
if (!req.file) {
return res.status(400).send({ message: 'No file uploaded' });
}
// Log file information (optional)
console.log('File received:', req.file);
// Send file back as response
res.setHeader('Content-Type', req.file.mimetype);
res.sendFile(path.resolve(req.file.path));
} catch (err) {
console.error('Error handling file upload:', err);
res.status(500).send({ message: 'Error processing file' });
}
});
const server = http.createServer(app);
const io = new Server(server, {
cors: {
2024-12-18 15:37:00 +03:00
origin: '*', // Adjust frontend URL if necessary
2024-12-18 15:19:55 +03:00
methods: ['GET', 'POST'],
},
2024-12-18 15:37:00 +03:00
maxHttpBufferSize: 1e8,
2024-12-18 15:19:55 +03:00
});
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
socket.on('sendFile', (data) => {
console.log('File received:', data.filename);
// Echo the file back to the frontend
socket.emit('receiveFile', data);
});
socket.on('disconnect', () => {
console.log('A user disconnected:', socket.id);
});
});
server.listen(8888, () => {
console.log('WS listening on port 8888');
2024-12-18 15:37:00 +03:00
});