server.js 1.33 KB
Newer Older
우지원's avatar
우지원 committed
1
2
3
import express from 'express'
import connectDb from './utils/connectDb.js'
import userRouter from './routes/user.routes.js'
4
import authRouter from './routes/auth.routes.js'
Soo Hyun Kim's avatar
Soo Hyun Kim committed
5
import roomRouter from './routes/room.routers.js'
6
7
8
import bodyParser from "body-parser";
import http from "http";
import { Server } from 'socket.io';
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
9
import cors from "cors"
10

우지원's avatar
우지원 committed
11
connectDb()
Choi Ga Young's avatar
Choi Ga Young committed
12

우지원's avatar
우지원 committed
13
const app = express()
Choi Ga Young's avatar
Choi Ga Young committed
14

15
16
17
18
19
20
21
const server = http.createServer(app);

const io = new Server(server)

io.on("connection", (socket) => { // 기본 연결
  console.log("socket connect ok", socket.id)

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
22
23
  socket.on('joinRoom', (data)=>{ // joinRoom을 클라이언트가 emit했을 때
    let roomName=data;
24
25
26
27
28
    socket.join(roomName); //클라이언트에서 data에 적힌 room으로 참여시킴
  });

  socket.on('chat', (data) => {
    console.log(`chat실행 :`, data.roomName, data.msg)
JeongYeonwoo's avatar
D    
JeongYeonwoo committed
29
    io.to(data.roomName).emit('broadcast', [data.msg, data.name]); //roomName에 존재하는 모든 소켓들에게 
30
31
32
33
34
  })

  socket.on('disconnect', () => {
    console.log('disconnected from server id=', socket.id)
  })
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
35
  
36
37
38
});

// app.use(express.json())
우지원's avatar
우지원 committed
39
//이부분을 body 파싱함
40
app.use(bodyParser.json());
41
app.use(cors());
42

우지원's avatar
우지원 committed
43
app.use(userRouter)
44
app.use(authRouter)
45
app.use(roomRouter)
Choi Ga Young's avatar
Choi Ga Young committed
46

JeongYeonwoo's avatar
JeongYeonwoo committed
47
server.listen(3030, () => {
48
  console.log('Listening on port 3030')
49
})
50

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
51
export default server
52
// module.exports = server;