node express

김주빈·2020년 4월 10일
0

socket

목록 보기
1/1

express 를 사용하기 전에는 socket io 를 적용시키는데 성공했지만 ( 억지로 성공한것 같다.)
express 로 refactor 을 하기 시작하면서 socket io 기능에서 문제가 생겼다.

const app = require('express')();
const http = require('http').createServer(app);
const PORT = process.env.NODE_ENV === 'production' ? 3001 : 3002;
const io = require('socket.io')(http);
const path = require('path');

const messages = require('./messages');
const clientPath = path.resolve(
  __dirname + 'client_directory'
);

app.use(express.static(clientPath));

app.get('/', (req, res, next) => {
  console.log('GET I ?');
  res.sendFile(clientPath + '/index.html');
});
<-index.html->

<script src="/socket.io/socket.io.js"></script>
<script src="scripts/app.js"></script>

예상

localhost:3002 번으로 접속을 할경우 내 예상으로는

// GET I ? 
// res.sendFile 을 통해 index.html 이 실행
// index html 에서 script src 를 읽어오는 와중에 socket io err
// arr.js 호출

결과

// app.use(expree.static) 으로 인해 client_directory 를 불러낸다
// script src = socket.io/socket.io.js 를 GET으로 불러오며 err (404 error)
// app.js 호출
// app.get  '/' 를 호출하지 않는다!!

해결

1. app.get

script src = socket.io 로 하고 get 으로 호출을 할 경우 서버파일의 socket.io를 send 해주는것 이다.

app.get('/socket.io/socket.io.js', (req, res) => {
  res.sendFile(
    path.resolve(
      __dirname + '/../node_modules/socket.io-client/dist/socket.io.js'
    )
  );
});
app.get('/socket.io/socket.io.js.map', (req, res) => {
  res.sendFile(
    path.resolve(
      __dirname + '/../node_modules/socket.io-client/dist/socket.io.js.map'
    )
  );
});

실패

2. static 을 css 만 적용한다.

app.use('/styles', express.static(clientPath + '/styles'));
app.use('/scripts', express.static(clientPath + '/scripts'));

// 결과
//GET http://localhost:3002/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)

3. socket.io 비교

socket.io 에 나와있는 자료와 비교를 하다보니 하나의 큰 차이점을 찾게 되었다.

// my file
const app = require('express')()

app.listen(PORT, () => {
  console.log(`server listen on ${PORT}`);
});

// socket.io example
var http = require('http')

http.listen(PROT, () => {
  console.log('server listen on' + PROT);
});

결과

const app = require('express')();
1. var http = require('http').Server(app) 를 하고
app.listen(...) 을 하였기 때문에 나는 에러였다.

//수정후 

const server = app.listen(PORT);
const io = require('socket.io').listen(server);
io.on(...)

참고 https://stackoverflow.com/questions/17696801/express-js-app-listen-vs-server-listen

profile
프론트엔드 개발자 김 주빈 입니다.

0개의 댓글