#socket.io chat 숙제하기 1
위 사이트에 맨 마지막 부분에 아래와 같은 내용이 있어 하나씩 해 보기로 한다.
Homework
Here are some ideas to improve the application:
- Broadcast a message to connected users when someone connects or disconnects.
- Add support for nicknames.
- Don’t send the same message to the user that sent it. Instead, append the message directly as soon as he/she presses enter.
- Add “{user} is typing” functionality.
- Show who’s online.
- Add private messaging.
- Share your improvements!
1. 누군가 접속을 하거나 나갔을때 알려 주기
원본 소스에 추가하는 형태로 하겠다.
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
socket.emit('chat message','welcome')
// 접속되어 있는 모든이에게 새로운 접속자가 있다고 알린다.
// Broadcast 로 전송하는데 신규로 접속한 창에는 전송하지 않는다.
socket.broadcast.emit('chat message','broadcast welcome')
socket.on('chat message', msg => {
console.log('chat message',msg)
io.emit('chat message', msg);
});
// 창을 닫으면 전달한다. 나갈때 사용
socket.on('disconnect',() => {
io.emit('chat message','A user has left the chat')
})
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});
추가된 부분 1
io.on('connection', (socket) => {
socket.emit('chat message','welcome')
socket.broadcast.emit('chat message','broadcast welcome')
내용은
접속하면 io.on('connection' 이 호출되고 접속한 socket 이 파라메타가 되어
socket.emit을 실행하고 그러면 자신의 socket.on 을 호출하여 welcome 을 출력하고
broadcast.emit 을 하여 자신을 제외한 모든 접속자에 socket.on을 호출한다.
추가된 부분 2
socket.on('disconnect',() => {
io.emit('chat message','A user has left the chat')
})
내용은 disconnect 가 발생한 경우
io.emit 을 이용하여 나머지 접속된 사용자에게 socket 이 하나 끊어졌다고 알려주는 내용이다.
정리하면
서버는 신규 socket 이 생성되면 ( 사용자가 접속을 하면 )
생성된 socket에게만 socket.emit('chat message','welcome') 하고 ( 접속을 환용한다는 내용 전송 )
나머지한테는 socket.broadcast.emit('chat message','broadcast welcome') 한다. ( 신규 접속을 알림 )
socket.on('chat mesage',msg) 을 통하여 사용자에게 받은 내용을
io.emit('chat message',msg) 를 이용해서 모든 사용자 창에 전달한다.
그리고, 접속이 끊어지면 socket.on('disconnect' 가 자동으로 서버로 넘어오고
서버는 emit.on('chat message',를 이용해서 나머지에게 접속이 끊어진 것을 알려주는 내용이다.
클라이언트에서는 아무것도 수정할 내용이 없다.
그냥 서버쪽에서 자신에게 접속한 socket 의 정보를 이용해서 처리하였을 뿐이다.
아래는 실행한 결과에 대한 영상이다.
댓글
댓글 쓰기