본문 바로가기

카테고리 없음

[JAS] Web Socket 패키지 설정

 

1. socket.io 모듈을 다운 받아준다.

 

npm install socket.io

 

const socket = require('socket.io');

 

 

 

2. http 라이브러리 사용

 

web socket을 사용할때에는 express 사용이 안돼서 http라이브러리를 사용해 줘야한다.

socket과 연결해서 http 문서를 읽기 위해서 사용함.

 

const http = require('http');

 

다만 http 라이브러리는 이미 node.js의 내장 모듈로서 존재하기 때문에 따로 install을 할 필요는 없다.

 

 

 

3. 서버 생성

 

http method인 createServer 메서드를 사용해서 express와 연결된 server를 생성해준다.

 

const server = http.createServer(app);

 

 

 

4. socket과 server를 연결해준다.

 

const io = socket(server);

 

 

 

5. 클라이언트에서도 socket을 사용할 수 있는 환경을 만들어 준다.

 

5-1. node_modules안에 socket.io아에 client-dist안에 있는 socket.io.js 파일을 연결해주기 위해 해당 파일 위치로 static을 사용한다.

 

app.use(express.static('node_modules/socket.io/client-dist'));

 

5-1. html페이지에서 불러준다.

 

<script type="text/javascript" src="socket.io.js"></script>