2025-01-26T02:15:33
This commit is contained in:
130
doc/14_네트워크_통신.md
Normal file
130
doc/14_네트워크_통신.md
Normal file
@@ -0,0 +1,130 @@
|
||||
# 네트워크 통신
|
||||
|
||||
* fetch:
|
||||
최신 HTTP 요청 처리 방식으로 간단하고 Promise 기반이며, 대부분의 API 호출에 적합.
|
||||
* XMLHttpRequest:
|
||||
오래된 HTTP 요청 방식으로 여전히 지원되지만, 가독성과 유지보수 측면에서 권장되지 않음.
|
||||
* WebSocket:
|
||||
서버와 클라이언트 간 실시간 양방향 통신을 처리하며, 채팅 애플리케이션, 게임, 실시간 알림 등에 적합.
|
||||
|
||||
필요에 따라 단방향 API 호출에는 fetch를, 실시간 데이터 통신에는 WebSocket을 사용하는 것이 가장 적합합니다.
|
||||
|
||||
## fetch API
|
||||
|
||||
fetch는 네트워크 요청을 보내고 응답을 처리하기 위한 최신 JavaScript API입니다.
|
||||
이전의 XMLHttpRequest보다 간결하고 Promise 기반으로 작성되어 비동기 처리가 더 쉽습니다.
|
||||
|
||||
* Promise 기반 : .then()과 async/await를 사용하여 비동기 요청을 처리.
|
||||
* JSON 및 텍스트 처리 간편 : 응답 데이터를 간편하게 JSON으로 변환 가능.
|
||||
* 더 직관적이고 간결한 문법 : 코드 가독성이 높음.
|
||||
|
||||
### GET 요청
|
||||
```javascript
|
||||
fetch("https://api.example.com/data")
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error("Network response was not ok");
|
||||
}
|
||||
return response.json(); // JSON 데이터 변환
|
||||
})
|
||||
.then((data) => console.log(data)) // 데이터 처리
|
||||
.catch((error) => console.error("Fetch error:", error));
|
||||
```
|
||||
### POST 요청
|
||||
```javascript
|
||||
fetch("https://api.example.com/data", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ name: "Alice", age: 25 }),
|
||||
})
|
||||
.then((response) => response.json())
|
||||
.then((data) => console.log(data))
|
||||
.catch((error) => console.error("Fetch error:", error));
|
||||
```
|
||||
|
||||
## XMLHttpRequest
|
||||
XMLHttpRequest는 자바스크립트의 오래된 네트워크 요청 API입니다.
|
||||
AJAX 기술의 핵심 요소로, 웹 애플리케이션에서 서버와 비동기적으로 데이터를 교환할 수 있게 해줍니다.
|
||||
|
||||
* 오래된 기술
|
||||
- 2000년대 초반부터 사용된 API.
|
||||
- 아직도 일부 프로젝트에서 사용되지만, 새로운 프로젝트에는 fetch를 권장.
|
||||
* 비교적 복잡한 문법
|
||||
- 이벤트 기반 방식으로 동작하여 코드가 장황해질 수 있음.
|
||||
|
||||
### GET 요청
|
||||
```javascript
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("GET", "https://api.example.com/data", true);
|
||||
|
||||
xhr.onload = function () {
|
||||
if (xhr.status === 200) {
|
||||
console.log(JSON.parse(xhr.responseText)); // JSON 데이터 처리
|
||||
} else {
|
||||
console.error("Request failed with status:", xhr.status);
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = function () {
|
||||
console.error("Network error occurred");
|
||||
};
|
||||
|
||||
xhr.send();
|
||||
```
|
||||
### POST 요청
|
||||
|
||||
```javascript
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("POST", "https://api.example.com/data", true);
|
||||
xhr.setRequestHeader("Content-Type", "application/json");
|
||||
|
||||
xhr.onload = function () {
|
||||
if (xhr.status === 200) {
|
||||
console.log(JSON.parse(xhr.responseText));
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = function () {
|
||||
console.error("Network error occurred");
|
||||
};
|
||||
|
||||
xhr.send(JSON.stringify({ name: "Alice", age: 25 }));
|
||||
```
|
||||
|
||||
## WebSocket
|
||||
WebSocket은 서버와 클라이언트 간의 양방향, 실시간 통신을 위한 프로토콜입니다.
|
||||
HTTP는 요청-응답 기반으로 작동하지만, WebSocket은 연결이 유지되면서 데이터를 주고받을 수 있습니다.
|
||||
|
||||
* 양방향 통신
|
||||
- 클라이언트와 서버가 서로 데이터를 실시간으로 주고받을 수 있음.
|
||||
* 상태 유지(Connection)
|
||||
- 연결이 유지되는 동안 빠르고 효율적인 데이터 전송 가능.
|
||||
* 낮은 대기 시간
|
||||
- 실시간 애플리케이션(채팅, 게임 등)에 적합.
|
||||
|
||||
```javascript
|
||||
const socket = new WebSocket("wss://example.com/socket");
|
||||
|
||||
// 연결 성공 시 호출
|
||||
socket.onopen = function () {
|
||||
console.log("WebSocket connection established");
|
||||
socket.send("Hello, Server!");
|
||||
};
|
||||
|
||||
// 메시지 수신 시 호출
|
||||
socket.onmessage = function (event) {
|
||||
console.log("Message from server:", event.data);
|
||||
};
|
||||
|
||||
// 에러 발생 시 호출
|
||||
socket.onerror = function (error) {
|
||||
console.error("WebSocket error:", error);
|
||||
};
|
||||
|
||||
// 연결 종료 시 호출
|
||||
socket.onclose = function () {
|
||||
console.log("WebSocket connection closed");
|
||||
};
|
||||
```
|
||||
Reference in New Issue
Block a user