Jelajahi Sumber

start socket server

unknown 2 tahun lalu
induk
melakukan
fdeabe489a
2 mengubah file dengan 17 tambahan dan 13 penghapusan
  1. 17 8
      app.js
  2. 0 5
      bin/server.js

+ 17 - 8
app.js

@@ -1,10 +1,9 @@
 const express = require('express');
 const app = express();
-const server = require('http').createServer(app);
+const http = require('http');
 const { Server } = require('socket.io');
-const io = new Server(server);
-const logger = require('morgan');
 const cors = require('cors');
+const logger = require('morgan');
 const helmet = require('helmet');
 const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short';
 
@@ -12,14 +11,24 @@ app.use(helmet());
 app.use(logger(formatsLogger));
 app.use(cors());
 
-app.get('/', (_, res) => {
-	res.sendFile(__dirname + '/index.html');
+const server = http.createServer(app);
+
+const io = new Server(server, {
+	cors: {
+		origin: '*',
+		methods: ['GET', 'POST'],
+	},
 });
 
 io.on('connection', (socket) => {
-	console.log('a user connected');
-	socket.on('disconnect', () => {
-		console.log('user disconnected');
+	console.log(`User Connected: ${socket.id}`);
+
+	socket.on('join_room', (data) => {
+		socket.join(data);
+	});
+
+	socket.on('send_message', (data) => {
+		socket.to(data.room).emit('receive_message', data);
 	});
 });
 

+ 0 - 5
bin/server.js

@@ -1,14 +1,9 @@
 const server = require('../app');
 const db = require('../model/db');
-const createFolderIsExist = require('../helpers/create-directory');
 const PORT = process.env.PORT || 3001;
 
 db.then(() => {
 	server.listen(PORT, async () => {
-		const DIR_UPLOAD = process.env.DIR_UPLOAD;
-		const DIR_STATIC = process.env.DIR_STATIC;
-		await createFolderIsExist(DIR_UPLOAD);
-		await createFolderIsExist(DIR_STATIC);
 		console.log(`Server running. Use our API on port: ${PORT}`);
 	});
 }).catch((err) => {