1화 주소
https://centbin-dev.tistory.com/8
Github 서버 코드 주소입니다.
https://github.com/ac9831/dart_server_project
1화에 이어서 서버 코드를 작성해 보았습니다. 간단하게 분석해보죠.
import 'dart:io';
import 'dart:convert';
Future main() async {
var server = await HttpServer.bind(
InternetAddress.loopbackIPv4,
4040,
);
print('Listeningon localhost:${server.port}');
await for (HttpRequest request in server) {
handleRequest(request);
}
}
import 는 동일합니다. io와 convert를 사용했습니다.
main 코드에서는 HttpServer를 사용하여 주소 및 포트를 설정했습니다. 이 함수를 통해 서버를 올릴 수 있습니다. print 메서드를 통해 서버 주소와 포트를 출력합니다. ${}를 통해 변수의 값을 출력할 수 있다는 것을 알 수 있습니다.
for문을 통해 서버에서 요청이 오는 HttpRequest를 처리하도록 작성했습니다. handleRequest라는 메서드에 request를 넣어줬네요. handleRequest를 메서드를 보겠습니다.
void handleRequest(HttpRequest request) {
try {
if (request.method == 'GET') {
if (request.uri.pathSegments.elementAt(0) == 'site') {
handleGet(request);
}
} else if (request.method == 'POST') {
handlePost(request);
} else {
request.response
..statusCode = HttpStatus.methodNotAllowed
..write('Unsupported request: ${request.method}.')
..close();
}
} catch (e) {
print('Exception in handleRequest : $e');
}
}
HttpRequest를 파라미터로 받아서 request 특징별로 처리 로직을 다르게 작성했습니다.
request에서 가지고 있는 method 값을 가져와서 먼저 'Get', 'Post'별로 처리를 추가했습니다. handleXXX 함수를 호출를 합니다. 또한 그 외의 호출에 대해서는 지원하지 않는 요청이라는 메세지로 처리했습니다.
void handleGet(HttpRequest request) {
final response = request.response;
response
..writeln('Hi! This is Get Call!')
..close();
}
handleGet 메서드는 method가 get은 요청을 처리합니다. response에 writeln를 body로 적어서 응답합니다. 클라이언트는 서버가 보내준 응답을 받게 됩니다.
void handlePost(HttpRequest request) async {
ContentType contentType = request.headers.contentType;
HttpResponse res = request.response;
if (contentType?.mimeType == 'application/json') {
try {
String content = await utf8.decoder.bind(request).join();
var data = jsonDecode(content) as Map;
var fileName = request.uri.pathSegments.last;
await File(fileName).writeAsString(content, mode: FileMode.write);
res
..statusCode = HttpStatus.ok
..write('Wrote data for ${data['name']}.');
} catch (e) {
res
..statusCode = HttpStatus.internalServerError
..write("Exception during file I/O: $e.");
}
} else {
res
..statusCode = HttpStatus.methodNotAllowed
..write("Unsuported request: ${request.method}.");
}
await res.close();
}
handlePost는 contentType과 response를 따로 나누었습니다.
ContentType에서 json 형식을 줬는지 확인을 하는 코드를 추가했습니다. json 형식이 아니라면 잘못된 요청으로 돌려줍니다.
Data를 받고 JsonDecode를 사용해서 변환을 합니다. fileName을 path의 가장 마지막 값으로 지정합니다. 그리고 File 함수를 통해 받은 data를 File에 쓰고 저장합니다. 문제 없이 진행되었다면, 클라이언트에게 ok를 보내기 위해 response에 status code와 body를 작성합니다.
마지막으로 response.close를 통해 응답합니다.
위와 같이 서버에 file.txt가 생성되고, 클라이언트가 전달한 내용이 작성되어 저장 됩니다.
이렇게 간단한 Dart로 서버와 클라이언트 통신을 구현해 보았습니다. 다음에는 Flutter에서 통신하는 프로젝트를 소개하도록 하겠습니다. 참고로 여기서 쓴 io와 async 라는 패키지를 기반으로 만든 http 패키지를 통해 Flutter에서는 작성하게 됩니다.
'개발이야기 > Flutter + Dart' 카테고리의 다른 글
[Flutter] Provider 패턴 (0) | 2020.02.25 |
---|---|
[Flutter] Firebase 연동 - google Login (0) | 2020.02.20 |
[Flutter] AndroidX 마이그레이션 문제 해결 방법 (0) | 2020.02.19 |
Dart로 Server와 Client 만들기 - 1화 (0) | 2019.11.17 |
Flutter 앱 시작하기 - Windows 10 + VS Code 환경 (0) | 2019.10.03 |
댓글