기록/수강내용
210924 웹소켓사용하여 채팅구현하기
코드코코
2021. 9. 26. 22:24
*웹소켓 : 실시간 양방향 통신지원
1. soket.io
-soket.io모듈의 메서드
-on: 소켓 이벤드 연결
-emit: 소켓 이벤트를 발생
2. 소켓통신종류
-public : 자신을 포함한 모든 클라이언트에 데이터를 전달
-broadcast:자신을 제외한 모든 클라이언트에 데이터를 전달
-private : 특정 클라이언트에 데이터를 전달
-----------------------------------------------------------------------------------------------------------------------------------
1. npm i socket.io@1 설치
- socket.io로 설치 안한 이유는 1.7.4 버전을 사용하기 위해서
- 호환성에대한 이유로 최신버전 사용안함.
2. html 작성
<!DOCTYPE html>
<html lang="ko">
<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="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
//html문서가 로드가 되면 변수선언
$(document).ready(() => {
const socket = io.connect();
socket.on('message', (data) => {
//추가할 문자열
let output = '';
output += '<li>';
output += ' <h3>' + data.name + '</h3>';
output += ' <p>' + data.message + '</p>';
output += ' <p>' + data.date + '</p>';
output += '</li>';
//문서 객체 추가
$(output).prependTo('#content')
//$('#content').listview('refresh');
});
$('button').click(() => {
socket.emit('message', {
name: $('#name').val(),
message: $('#message').val(),
date: new Date().toUTCString(),
});
});
});
</script>
</head>
<body>
<h1>이야기공간</h1>
<p>노드와 함께하는 채팅</p>
<hr>
<input id="name">
<input id="message">
<button>전송</button>
<ul id="content"></ul>
</body>
</html>
3. app.js 작성
const http = require('http');
const fs = require('fs');
const socketio = require('socket.io');
const server = http.createServer((req, res) => {
fs.readFile('Page.html', (error, data) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
});
})
.listen(3000, () => {
console.log('3000번 포트 대기중');
});
//소켓서버를 생성하고 실행
const io = socketio.listen(server);
//소켓서버 생성 후 에 이벤트연결
//connection->클라이언트가 웹 소켓 서버에 접속할 때 발생
io.sockets.on('connection', (socket) => {
socket.on('message', (data) => {
//public : 자신을 포함한 모든 클라이언트에 데이터 전달
io.sockets.emit('message', data);
})
})
4. 결과물 : 창을 2개 열어서 확인해 보니 아래와 같이 출력됨!
