
강의 #2
웹소켓 선언하기
웹소켓이란?
- 웹소켓은 서버와 브라우저 사이에 양방향 소통이 가능함
- 클라이언트 측에서 별도의 요청을 보내지 않아도 데이터를 수신할 수 있음
- 지속적으로 업데이트되는 정보를 수신해야 하는 채팅이나 주식 보고서에서 이점이 있음
require 함수
- node.js에서 외부 모듈을 가져오기 위해 쓰는 함수
const foo = require('파일 경로');
ws module
ws.on("connection", function connect(ws, req) {
console.log("NEW USER CONNECT");
});
- connection 이벤트가 발생했을 때 작동시킬 내용을 함수로 넘겨줌
xampp 세팅
xampp 설치
brew install --cask xampp

php 설정
jquery cdn
최종 코드
서버
const WebSocket = require("ws");
const ws = new WebSocket.Server({ port:8008 });
ws.on("connection", function connect(ws, req) {
console.log("NEW USER CONNECT");
});
클라이언트
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
function connect() {
let websocket = new WebSocket("ws://localhost:8008");
}
connect();
</script>
</head>
<body>
</body>
</html>

- node 명령어로 index.js 실행 후 클라이언트가 연결되면 console에 메세지가 출력됨