티스토리 뷰

Node.js

socket.io 시작

LHOIKTN 2021. 7. 4. 15:35

https://www.tutorialspoint.com/socket.io/index.htm

 

Socket.IO Tutorial - Tutorialspoint

Socket.IO Tutorial Socket.IO enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. Socket.IO is built on top of the WebSockets API (Client side) and Node.js. It

www.tutorialspoint.com

여기를 참고했음

 

 

소켓.IO는 실시간 양방향 이벤트 기반 통신을 가능하게 한다. 

 

먼저 npm init 

npm install express, nunjucks. body-parser, socket.io 를 설치해준다. 

서버 계속 끄고 켜고. 이거 하기 싫으면 

npm install -g nodemon  설치해준다.   설치하면 node app.js 대신에 nodemon app.js를 사용할 수 있다. 

이렇게하면 파일을 변경할 때마다 서버를 재시작할 필요가 없다^^ 

 

기본 셋팅 

 

app.js

const express = require('express')
const app = express();
const bodyParser = require('body-parser');
const nunjucks = require('nunjucks');
const socket = require('socket.io');
const http = require('http'); 
const server = http.createServer(app);
//http.Server(app);
const io = socket(server);



app.set('view engine', 'html')
nunjucks.configure('views', {
  express: app
})

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


app.get('/', (req, res) => {
  res.render('index.html');
})


io.on('connection', (socket) => {
  console.log('A user connected');

  socket.on('disconnect', () => {
    console.log('A user disconnected');
  })

})


server.listen(3000, () => {
  console.log(`hello port 3000`);
})

 

veiws > index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src = "/socket.io/socket.io.js"></script>
   
  <script>
     const socket = io();
  </script>
</head>
<body>
  바쁜 벌꿀은
</body>
</html>

 

이렇게 셋팅해주고 브라우져에서 locallhost:3000 에 접속한 다음 server의 콘솔창을 확인하면 

 접속한 브라우저에서 F5 눌러서 새로고침을 해보면 소켓 연결이 끊겼다가 다시 생성된다. 

 

 

 

728x90

'Node.js' 카테고리의 다른 글

socket.io 브로드캐스팅  (0) 2021.07.04
socket.io 이벤트  (0) 2021.07.04
unload 이벤트, navigator.sendBeacon()  (0) 2021.06.22
게시판 테이블.  (0) 2021.06.09
0527 수업내용.  (0) 2021.05.27
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함