server.js 1.26 KB
Newer Older
우지원's avatar
우지원 committed
1
2
import express from 'express'
import connectDb from './utils/connectDb.js'
Soo Hyun Kim's avatar
Soo Hyun Kim committed
3
import roomRouter from './routes/room.routers.js'
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
4
5
6
7
import cors from "cors"
import bodyParser from "body-parser"
import http from 'http'
import { Server } from 'socket.io'
Choi Ga Young's avatar
Choi Ga Young committed
8

우지원's avatar
우지원 committed
9
connectDb()
Choi Ga Young's avatar
Choi Ga Young committed
10

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

우지원's avatar
우지원 committed
13
app.use(express.json())
Soo Hyun Kim's avatar
Soo Hyun Kim committed
14
app.use(roomRouter)
Choi Ga Young's avatar
Choi Ga Young committed
15

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
16
17
18
19
20
21
22
23
24
25
const server = http.createServer(app);

const io = new Server(server);

// const port = process.env.PORT || 3001; // 3001 수정해야하나?

app.use(bodyParser.json());

app.use(cors());
// app.use('/', indexRouter);
Soo Hyun Kim's avatar
Soo Hyun Kim committed
26

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
27
28
io.on("connection", (socket) => { // 기본 연결
  console.log("socket connect ok", socket.id)
Choi Ga Young's avatar
Choi Ga Young committed
29

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  socket.on('joinRoom', (data)=>{ // joinRoom을 클라이언트가 emit했을 때
    let roomName=data;
    socket.join(roomName); //클라이언트에서 data에 적힌 room으로 참여시킴
  });

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

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

server.listen(3030, () => {
우지원's avatar
우지원 committed
46
    console.log('Listening on port 3030')
47
})
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
48
49
50
51
// server.listen(port, () => { console.log(`Listening on port ${port}`) });

export default server
// module.exports = server;