반응형
96. 간단한 웹 서버 만들기: Dart로 간단한 웹 서버를 구현하고 요청에 응답하세요.
문제
Dart를 사용하여 간단한 웹 서버를 만들고, 클라이언트의 요청에 대해 응답을 반환하세요.
풀이
Dart의 dart:io 패키지를 사용하여 간단한 웹 서버를 구현할 수 있습니다.
import 'dart:io';
Future<void> main() async {
final server = await HttpServer.bind(
InternetAddress.anyIPv4,
8080,
);
print('웹 서버가 8080 포트에서 실행 중입니다.');
await for (HttpRequest request in server) {
request.response
..write('Hello, Dart!')
..close();
}
}
설명
- HttpServer.bind를 사용해 서버를 지정된 IP 주소와 포트에 바인딩합니다.
- 서버가 요청을 받을 때마다 request.response.write를 통해 응답을 작성하고, close를 호출하여 응답을 완료합니다.
- 위 예제에서는 클라이언트가 서버에 요청을 보낼 때마다 "Hello, Dart!"라는 메시지를 응답으로 반환합니다.
97. 웹 요청 핸들링: 웹 요청을 처리하여 HTML 응답을 반환하세요.
문제
웹 서버에서 클라이언트의 요청을 처리하고, 간단한 HTML 페이지를 응답으로 반환하세요.
풀이
요청된 URL에 따라 HTML 응답을 반환하도록 웹 서버를 확장할 수 있습니다.
import 'dart:io';
Future<void> main() async {
final server = await HttpServer.bind(
InternetAddress.anyIPv4,
8080,
);
print('웹 서버가 8080 포트에서 실행 중입니다.');
await for (HttpRequest request in server) {
if (request.uri.path == '/') {
request.response
..headers.contentType = ContentType.html
..write('<html><body><h1>Welcome to Dart Web Server!</h1></body></html>');
} else {
request.response
..statusCode = HttpStatus.notFound
..write('404 Not Found');
}
await request.response.close();
}
}
설명
- 요청된 경로가 /인 경우 간단한 HTML 페이지를 반환합니다.
- ContentType.html을 설정하여 응답의 콘텐츠 유형이 HTML임을 명시합니다.
- 잘못된 경로로 접근 시 404 상태 코드와 함께 "404 Not Found" 메시지를 반환합니다.
98. JSON API 구현하기: JSON 형식의 데이터를 반환하는 API를 구현하세요.
문제
Dart를 사용하여 JSON 형식의 데이터를 반환하는 API를 구현하세요.
풀이
Dart의 dart:convert 패키지를 사용하여 JSON 데이터를 처리하고 API 응답으로 반환할 수 있습니다.
import 'dart:io';
import 'dart:convert';
Future<void> main() async {
final server = await HttpServer.bind(
InternetAddress.anyIPv4,
8080,
);
print('웹 서버가 8080 포트에서 실행 중입니다.');
await for (HttpRequest request in server) {
if (request.uri.path == '/api/data') {
final data = {
'name': 'Alice',
'age': 30,
'city': 'New York'
};
final jsonResponse = jsonEncode(data);
request.response
..headers.contentType = ContentType.json
..write(jsonResponse);
} else {
request.response
..statusCode = HttpStatus.notFound
..write('404 Not Found');
}
await request.response.close();
}
}
설명
- jsonEncode를 사용해 Dart의 Map을 JSON 형식으로 변환합니다.
- ContentType.json을 설정하여 응답의 콘텐츠 유형이 JSON임을 명시합니다.
- /api/data 경로로 요청이 들어오면 JSON 데이터를 응답으로 반환합니다.
99. 클라이언트와 서버 간 데이터 전송: 클라이언트와 서버 간 데이터 전송을 구현하세요.
문제
Dart를 사용하여 클라이언트와 서버 간에 데이터를 주고받는 프로그램을 구현하세요.
풀이
서버에서 JSON 데이터를 수신하고, 이를 처리한 후 응답하는 예제를 작성해보겠습니다.
import 'dart:io';
import 'dart:convert';
Future<void> main() async {
final server = await HttpServer.bind(
InternetAddress.anyIPv4,
8080,
);
print('웹 서버가 8080 포트에서 실행 중입니다.');
await for (HttpRequest request in server) {
if (request.uri.path == '/api/send' && request.method == 'POST') {
try {
final content = await utf8.decoder.bind(request).join();
final data = jsonDecode(content) as Map;
// 데이터 처리 (예: 클라이언트가 보낸 데이터 출력)
print('수신된 데이터: $data');
request.response
..statusCode = HttpStatus.ok
..write('Data received and processed.');
} catch (e) {
request.response
..statusCode = HttpStatus.internalServerError
..write('Failed to process data.');
}
} else {
request.response
..statusCode = HttpStatus.notFound
..write('404 Not Found');
}
await request.response.close();
}
}
설명
- POST 요청을 처리하고, utf8.decoder와 jsonDecode를 사용하여 수신된 JSON 데이터를 디코딩합니다.
- 클라이언트가 전송한 데이터를 서버에서 처리한 후 성공 메시지를 응답으로 반환합니다.
- 데이터 처리 중 에러가 발생하면 500 상태 코드와 에러 메시지를 반환합니다.
100. 웹 애플리케이션에서 상태 관리하기: 웹 애플리케이션에서 상태를 관리하고 상태 변화를 반영하세요.
문제
Dart에서 웹 애플리케이션의 상태를 관리하고, 상태 변화에 따라 사용자에게 업데이트된 정보를 제공하는 프로그램을 작성하세요.
풀이
간단한 카운터 애플리케이션을 만들어 상태 변화를 관리해보겠습니다.
import 'dart:io';
int counter = 0;
Future<void> main() async {
final server = await HttpServer.bind(
InternetAddress.anyIPv4,
8080,
);
print('웹 서버가 8080 포트에서 실행 중입니다.');
await for (HttpRequest request in server) {
if (request.uri.path == '/increment') {
counter++;
request.response
..headers.contentType = ContentType.html
..write('<html><body><h1>Counter: $counter</h1></body></html>');
} else if (request.uri.path == '/decrement') {
counter--;
request.response
..headers.contentType = ContentType.html
..write('<html><body><h1>Counter: $counter</h1></body></html>');
} else {
request.response
..statusCode = HttpStatus.notFound
..write('404 Not Found');
}
await request.response.close();
}
}
설명
- 전역 변수를 사용하여 카운터 상태를 유지합니다.
- /increment와 /decrement 경로로 요청이 들어오면 카운터 값을 증가 또는 감소시킵니다.
- 상태 변화에 따라 업데이트된 카운터 값을 HTML 형식으로 클라이언트에 반환합니다.
공감과 댓글은 저에게 큰 힘이 됩니다.
Starting Google Play App Distribution! "Tester Share" for Recruiting 20 Testers for a Closed Test.
Tester Share [테스터쉐어] - Google Play 앱
Tester Share로 Google Play 앱 등록을 단순화하세요.
play.google.com
반응형
'Dart > Dart 100제' 카테고리의 다른 글
Dart 100제 91 ~ 95 (데이터 처리) (0) | 2024.08.26 |
---|---|
Dart 100제 86 ~ 90 (실용문제) (0) | 2024.08.26 |
Dart 100제 81 ~ 85 (기타) (0) | 2024.08.26 |
Dart 100제 71 ~ 75 (라이브러리와 패키지) (0) | 2024.08.11 |
Dart 100제 66 ~ 70 (예외 처리) (0) | 2024.08.11 |