티스토리 뷰
연결된 모든 클라이언트에게 메시지를 보낼 때,
다음과 같은 두가지 방법을 사용할 수 있다.
- io.sockets.emit(event, object)
나를 포함한 모든 클라이이언트에게 메시지가 전송된다.
- socket.broadcast.emit(evnet, object)
나를 제외한 모든 클라이언트에게 메시지가 전송된다.
브로드캐스트를 연습할 때는 클라이언트가 여러개 필요한데, 그냥 크롬에서 여러개 키면, 여러개 켜도, 클라이언트가 하나다. 하나 킬때마다 앞에 소켓이 해제된다. ㅡㅡ;; 그래서 다른 브라우저, 파이어폭스, 엣지, 웨일, 뭐 이런거로 여러 클라이언트를 켰었는데,
크롬의 시크릿 창을 사용하면, 각 탭마다 클라이언트 소켓이 연결되어 보다 쉽게 브로트캐스트 연습을 할 수 있다.
io.sockets.emit(event,object) 연습
소켓은 emit을 통해 이벤트를 생성하고 실행하는데, 이 emit은 방출하다는 의미가 있다. 뭔가 가스를 내뿜는 느낌?
예전에 노가다할 때 밥 많이 쳐먹는 아저씨가 부대찌개 먹고 한 트림냄새를 맡고 토할뻔 한 게 생각난다. 내가 비위가 약한편이 아니라 토를 안했지. 좀 약한 사람이었으면 무조건 토했을 그런 냄새였다.
아무튼 그 아저씨가 부대찌개 먹고 트림을 emit 해서 접속한 모든 클라이언트가 트림냄새를 맡게 하는 예제를 만들어보면.
views > 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>
</head>
<body>
<input type="text" id="username">
<input type="text" id="userfood">
<button onclick="teulim()">끄윽</button>
<h1 id="h1"></h1>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
function teulim() {
const data = {};
data.username = document.querySelector('#username').value
data.userfood = document.querySelector('#userfood').value
socket.emit('teulim', data);
}
socket.on('teulim',(data)=>{
const h1 = document.querySelector('#h1')
h1.innerHTML =`~~~~${data.username}이(가) ${data.userfood}을(를) 먹고 emit한 더러운 트림 냄새~~~~`;
})
</script>
</body>
</html>
app.js
io.on('connection', (socket) => {
socket.on('teulim', (data) => {
io.sockets.emit('teulim', data)
});
})
이렇게 밥 많이 쳐먹는 아저씨가 부대찌개를 먹고, 끄윽 버튼은 누르면
이렇게 접속한 클라이언트에 전부 트림냄새를 보낼 수 있다.
socket.broadcast.emit(evnet, object)
위 예제에서는 자기가 트림했는데 자기한테도 냄새가 전해진다. 물론 자기도 그 냄새를 맡긴 하겠지만,
자신을 제외한 모든 클라이언트에게 emit하는 경우를 연습하기 위해 예제를 조금 바꾸면
views > 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>
</head>
<body>
<input type="text" id="username">
<input type="text" id="userfood">
<button onclick="teulim()">끄윽</button>
<h1 id="h1"></h1>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
function teulim() {
const data = {};
data.username = document.querySelector('#username').value
data.userfood = document.querySelector('#userfood').value
socket.emit('teulim', data);
/////////////////////////////////////////////////
const h1 = document.querySelector('#h1')
h1.innerHTML =`끄윽`;
/////////////////////////////////////////////
}
socket.on('teulim',(data)=>{
const h1 = document.querySelector('#h1')
h1.innerHTML =`~~~~${data.username}가(이) ${data.userfood}를(을) 먹고 emit한 역겨운 트림 냄새~~~~`;
})
</script>
</body>
</html>
이렇게 자기 트림소리 부분을 추가해주고.
app.js
io.on('connection', (socket) => {
socket.on('teulim', (data) => {
socket.broadcast.emit('teulim', data)
// io.sockets.emit('teulim', data)
});
})
브로드캐스트로 바꿔준다.
똑같이 실행하면
끄윽 버튼을 누른 클라이언트에게는 메시지가 전달되지 않은 것을 알 수 있다.
'Node.js' 카테고리의 다른 글
socket.io 팁 (0) | 2021.07.04 |
---|---|
socket.io 이벤트 (0) | 2021.07.04 |
socket.io 시작 (0) | 2021.07.04 |
unload 이벤트, navigator.sendBeacon() (0) | 2021.06.22 |
게시판 테이블. (0) | 2021.06.09 |
- Total
- Today
- Yesterday
- node.js
- 롱베케이션
- 투포인터
- 서버개발
- create db
- 투포인터 연습
- BFS
- 동적프로그래밍
- DB 생성
- create databases;
- 면접질문
- 면접비
- 최소공통조상
- 서버점검
- 은둔청년체험
- 개발자면접
- 다이나믹프로그래밍
- 다이나밍프로그래밍
- 그래프
- MOD
- 로드나인
- MySQL
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |