# 8회차

## Socket.io

* Node.js용 소켓프로그래밍 지원
* 서버와의 양방향 통신
* 클라이트와 서버와 연결
* 원리 : 서버와의 연결을 해놓고, 중간에 이벤트가 발생하면 클라이언트에 바로 반영
* 단방향 : 클라이언트가 setInterval로 지속적으로 체크
* 양방향 : 서버와 연결을 맺어놓고, 다른 사용자의 이벤트가 있을시 즉각반영&#x20;
* 작동 흐름

  1\) 웹페이지 접속

  2\) 클라이언트 var socket = io(); 로

  3\) 서버와 연결관계를 맺음

  4\) 서버에 이벤트로 emit

  5\) 전체 클라이언트에 메시지전달
* 서버측 구현

  1\) 소켓접속시 사용자 정보 갱신

```javascript
// userList에 내 정보가 없으면 삽입
if(userList.indexOf(user.username) === -1){
    userList.push(user.username);
}
```

2\) 채팅방 접속시

```javascript
    // 사용자 리스트 반환
    io.emit('join', userList);
```

3\) 채팅방 종료시

```javascript
    // 내 정보 삭제하고 사용자리스트 반환
    socket.on('disconnect', function(){            
    userList.removeByValue(user.username);
    io.emit('leave', userList);
});
```

4\) 채팅 메시지 보내는 경우

```javascript
    // 사용자 명과 메시지 같이 반환
    socket.on('chat message', function(data){
    io.emit('chat message', { message : data.message , username : user.username });
});

});
```

* 클라이언트측 구현

```javascript
    // 접속시 데이터를 update함수로 넘긴다
    socket.on('join', function(data){
        updateUserList(data);
    });
```

```javascript
    // 이탈시
    socket.on('leave', function(data){
        updateUserList(data);
    });
```

```javascript
    // 채팅방으로 조인
    socket.join('방이름')
```

```javascript
    // 채팅방으로 나감
    socket.leave('방이름')
```

```javascript
    // 귓속말 : 클라이언트에서 넘겨주거나 or 서버  측에서 상대소켓아이디를 알아냄
    io.sockets[socket.id]
```

## Nodejs 채팅모듈 종류

* npm websocket
* npm socket.io


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://incheol-jung.gitbook.io/docs/study/nodejs/2018-01-16-nodejs-8st.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
