server.js 1.72 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'
JeongYeonwoo's avatar
JeongYeonwoo committed
5
import profileRouter from './routes/profile.routes.js'
Choi Ga Young's avatar
Choi Ga Young committed
6

7
8
9
10
11
12
import cors from "cors";
import bodyParser from "body-parser";
import http from "http";
import { Server } from 'socket.io';


우지원's avatar
우지원 committed
13
connectDb()
Choi Ga Young's avatar
Choi Ga Young committed
14

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

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const server = http.createServer(app);

const io = new Server(server)


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


  socket.on('joinRoom', (data) => { // joinRoom을 클라이언트가 emit했을 때
    let roomName = data;
    console.log(roomName, "방 입장")
    socket.join(roomName); //클라이언트에서 data에 적힌 room으로 참여시킴

  });

  socket.on('chat', (data) => {
    console.log(`chat실행 :`, data.roomName, data.msg)
    io.to(data.roomName).emit('broadcast', data.msg); //roomName에 존재하는 모든 소켓들에게 
  })

  socket.on('disconnect', () => {
    console.log('disconnected from server id=', socket.id)
  })


});

// app.use(express.json())
우지원's avatar
우지원 committed
46
//이부분을 body 파싱함
47
48
49
50
app.use(bodyParser.json());

// app.use(cors());
// app.use('/', indexRouter);
우지원's avatar
우지원 committed
51
52
//express가 req.body라는곳을 자동으로만들어서 json형식으로 보낸것을 객체형식으로 넣음
//이부분 다음부터는 req.body라는 부분을 실행할 수 있음
Choi Ga Young's avatar
Choi Ga Young committed
53

우지원's avatar
우지원 committed
54
app.use(userRouter)
55
app.use(authRouter)
JeongYeonwoo's avatar
JeongYeonwoo committed
56
app.use(profileRouter)
우지원's avatar
우지원 committed
57
//userRouter로 이동
Choi Ga Young's avatar
Choi Ga Young committed
58

우지원's avatar
우지원 committed
59
app.get('/', (req, res) => {
60
  res.send('Hello World. 안녕하세요')
우지원's avatar
우지원 committed
61
})
Choi Ga Young's avatar
Choi Ga Young committed
62

JeongYeonwoo's avatar
JeongYeonwoo committed
63
server.listen(3030, () => {
64
  console.log('Listening on port 3030')
65
})
66
67
68
69
70
71
72

/////////////////////////////////////////////////////////




// export default server