본문 바로가기

Project/TIL

20.03.31 ShareBook TIL

socket.io를 사용하기 위해 포트를 하나 더 쓰는 건 그다지 좋지 않은 거 같아서 기존 포트에 새로운 /chat 경로를 추가해보기로 하였다.

import http from 'http';
import socket from 'socket.io';

const app: Application = express();

const server = http.createServer(app);
const io = socket.listen(server);

 

socket에 server를 지정해 줘서 io란 변수가 기존 사용하던 포트를 사용하도록 하였다.

app.get('/chat', (req: Request, res: Response) => {
  res.sendFile(__dirname + '/index.html');
});

 

http://localhost:4000/chat 경로에 작성된 html 파일을 로드시킨다.

io.of('/chat').on('connection', (socket: any) => {
  socket.on('chat message', (msg: string) => {
    console.log(`messages: ${msg}`);
    io.emit('chat message: ', msg);
  });
  // socket.on('disconnect', () =>
  //   console.log('A user has disconnected from the socket!'),
  // );
});

 

클라이언트로 이벤트를 emit(송신)한다.

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

 

기존에 사용하던 app.listen이 아니라 server.listen으로 변경한다.

<html>

 <script src="http://localhost:4000/socket.io/socket.io.js"></script>
  <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
  <script>
    $(function() {
      var socket = io('http://localhost:4000/chat');
      $('form').submit(function(e) {
        e.preventDefault(); // prevents page reloading
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
      });
      socket.on('chat message', function(msg) {
        $('#messages').append($('<li>').text(msg));
      });
    });
  </script>

 

콘솔에는 양방향으로 잘 작동하나 아직 이벤트 내용이 웹페이지에 랜더가 되지 않는다.

레퍼런스와 일단 똑같이 작성하여 랜더까지 되는 걸 확인하고 다시 최대한 서로 다른 점을 찾아보고 포트도 변경해보고 html을 수정도 해보았지만 이유를 잘 모르겠다.

'Project > TIL' 카테고리의 다른 글

20.04.02 ShareBook TIL  (0) 2020.04.02
20.04.01 ShareBook TIL  (0) 2020.04.01
20.03.30 ShareBook TIL  (0) 2020.03.31
20.03.29 ShareBook TIL  (0) 2020.03.29
20.03.28 ShareBook TIL  (0) 2020.03.29