멍발자의 개발
기본 문법 복습 (9) 입출력과 네트워크 본문
입출력
package jachap03;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class WriteFile {
public static void main(String[] args) throws IOException {
var msg = """
test
msg
""";
var p = Path.of("test.txt");
Files.writeString(p, msg); // (저장위치, 저장되는 문자열)
System.out.println(Files.size(p)); // 사이즈 구하기 (ex. 11 바이트)
System.out.println(msg); //파일 내용 출력
}
}
//결과
9
test
msg
Files.readString() 메소드 = 파일 내용을 문자열로 읽을 때 사용한다.
예외
파일명을 잘못 입력하였을 때
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class ReadFile {
public static void main(String[] args) throws IOException {
try {
var p = Path.of("test.txta");
String s = Files.readString(p);
System.out.println(s);
} catch (NoSuchFileException e) {
//throw new RuntimeException(e);
System.out.println("파일을 찾을 수 없음: " + e.getFile());
}
}
}
//결과
파일을 찾을 수 없음: test.txta
예외 던지기
throw 예외객체 = 비검사 예외로 던지고 싶을 때 사용하는 구문
웹 통신
import java.io.*;
import java.net.Socket;
public class WebClient {
public static void main(String[] args) throws IOException {
var domain = "example.com";
try(var sk = new Socket(domain, 80);
var pw = new PrintWriter(sk.getOutputStream());
var isr = new InputStreamReader(sk.getInputStream());
var bur = new BufferedReader(isr))
{
pw.println("GET / index.html HTTP/1.1");
pw.println("Host: " + domain);
pw.println();
pw.flush();
bur.lines().limit(18).forEach(System.out::println);
}
}
}
//결과
HTTP/1.0 505 HTTP Version Not Supported
Content-Type: text/html
Content-Length: 379
Connection: close
Date: Tue, 26 Apr 2022 03:24:50 GMT
Server: ECSF (oxr/830A)
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>505 - HTTP Version Not Supported</title>
</head>
<body>
<h1>505 - HTTP Version Not Supported</h1>
</body>
</html>
종료 코드 0(으)로 완료된 프로세스
HTTP 메소드
GET = 데이터 검색
POST = 데이터 보내기 (글 등록, 일부만 변경)
PUT = 데이터 작성 또는 재작성 (insert, update, 등 수정할 때 사용)
DELETE = 데이터 삭제
요청 헤더
Host = 액세스 중인 도메인 //헤더는 반드시 지정돼야 한다.
User-Agent = 브라우저 유형
Referer = 링크 소스
상태 코드
200 = 정상적으로 종료
403 = 보기 권한이 없음
404 = 정보를 찾을 수 없음
301, 302 = 리다이엑션
500 = 내부 서버 오류
응답헤더
Content-Type = 문서유형
Last-Modified = 최종 변경된 날짜 및 시간
Content-Length = 데이터 크기
HTTPS 웹 통신
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class WebClient2 {
public static void main(String[] args) throws IOException {
var domain = "naver.com";
SocketFactory factory = SSLSocketFactory.getDefault();
try (Socket sk = factory.createSocket(domain, 443);
var pw = new PrintWriter(sk.getOutputStream());
var isr = new InputStreamReader(sk.getInputStream());
var bur = new BufferedReader(isr))
{
pw.println("GET / index.html HTTP/1.1");
pw.println("Host: " + domain);
pw.println();
pw.flush();
bur.lines().limit(18).forEach(System.out::println);
}
}
}
//결과
HTTP/1.1 301 Moved Permanently
Server: NWS
Date: Tue, 26 Apr 2022 05:08:03 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Location: http://www.naver.com/%20index.html
Vary: Accept-Encoding,User-Agent
Referrer-Policy: unsafe-url
a2
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center> NWS </center>
</body>
</html>
종료 코드 0(으)로 완료된 프로세스
HTTP/ HTTPS => 보안이 적용됐는가, 안 됐는가의 차이다.
body.lines()
웹서버 만들기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer {
public static void main(String[] args) throws IOException {
var server = new ServerSocket(8880);
for(;;) {
try (Socket sk = server.accept();
var isr = new InputStreamReader(sk.getInputStream());
var bur = new BufferedReader(isr);
var w = new PrintWriter(sk.getOutputStream())) {
System.out.println("연결: " + sk.getInetAddress());
bur.lines()
.takeWhile(line -> !line.isEmpty())
.forEach(System.out::println);
w.println("""
HTTP/1.1 200 OK
Content-Type: text/html
<html><head><title>Hi!</title></head>
<body><h1>Hi!</h1>Sage!</body></html>
""");
}
}
}
}
//결과
~ 아무것도 뜨지 않음 ~
크롬에서 주소창에 "http://localhost:8880"을 입력하면
이런 창이 뜬다.
그리고 아무것도 뜨지 않았던 결과 창에 값이 뜰 것.
'STUDY > Java' 카테고리의 다른 글
정규식 표현 & 패턴 정리 (0) | 2022.04.28 |
---|---|
기초 문법 복습 (7) 메소드 (0) | 2022.04.21 |
문자열 조건 세기와 스트림 (0) | 2022.04.19 |
기초 문법 복습(6) (확장 for문, repeat문, 미로 게임) (0) | 2022.04.18 |
기본 문법 복습 (5) 클래스 메소드 (0) | 2022.04.15 |
Comments