From 68d50f463aea53e751c769404c05ea45ecedd4c6 Mon Sep 17 00:00:00 2001 From: DevDAN09 Date: Wed, 2 Oct 2024 12:20:19 +0900 Subject: [PATCH] fix:issue/20 --- README.md | 11 -- assignment/assign1_yujin.py | 22 --- .../simple_webserver/nayoung/article1.html | 10 - .../simple_webserver/nayoung/article2.html | 10 - .../simple_webserver/nayoung/article3.html | 10 - .../http/simple_webserver/nayoung/client.js | 41 ---- .../http/simple_webserver/nayoung/index.html | 12 -- .../http/simple_webserver/nayoung/server.js | 60 ------ .../simple_webserver/ym/homework_client.py | 50 ----- .../simple_webserver/ym/homework_server.py | 84 --------- .../simple_webserver/ym/src/article1.html | 39 ---- .../simple_webserver/ym/src/article2.html | 10 - .../simple_webserver/ym/src/article3.html | 10 - .../http/simple_webserver/ym/src/index.html | 48 ----- .../http/simple_webserver/yujin/article1.html | 12 -- .../http/simple_webserver/yujin/article2.html | 12 -- .../http/simple_webserver/yujin/article3.html | 12 -- .../http/simple_webserver/yujin/client.py | 32 ---- .../http/simple_webserver/yujin/index.html | 18 -- .../http/simple_webserver/yujin/server.py | 54 ------ .../article1.html" | 15 -- .../article2.html" | 15 -- .../article3.html" | 15 -- .../index.html" | 18 -- .../server.cpp" | 178 ------------------ ...4 \353\247\214\353\223\244\352\270\260.md" | 58 ------ assignment/os/thread/assign1_hwangon.py.md | 55 ------ .../assign2_seoneui/tcp_echo_client.cpp | 67 ------- .../assign2_seoneui/tcp_echo_server.cpp | 90 --------- .../assign2_seoneui/udp_echo_client.cpp | 69 ------- ...\352\270\260 (Blocking, None-Blocking).md" | 2 +- 31 files changed, 1 insertion(+), 1138 deletions(-) delete mode 100644 README.md delete mode 100644 assignment/assign1_yujin.py delete mode 100644 assignment/network/http/simple_webserver/nayoung/article1.html delete mode 100644 assignment/network/http/simple_webserver/nayoung/article2.html delete mode 100644 assignment/network/http/simple_webserver/nayoung/article3.html delete mode 100644 assignment/network/http/simple_webserver/nayoung/client.js delete mode 100644 assignment/network/http/simple_webserver/nayoung/index.html delete mode 100644 assignment/network/http/simple_webserver/nayoung/server.js delete mode 100644 assignment/network/http/simple_webserver/ym/homework_client.py delete mode 100644 assignment/network/http/simple_webserver/ym/homework_server.py delete mode 100644 assignment/network/http/simple_webserver/ym/src/article1.html delete mode 100644 assignment/network/http/simple_webserver/ym/src/article2.html delete mode 100644 assignment/network/http/simple_webserver/ym/src/article3.html delete mode 100644 assignment/network/http/simple_webserver/ym/src/index.html delete mode 100644 assignment/network/http/simple_webserver/yujin/article1.html delete mode 100644 assignment/network/http/simple_webserver/yujin/article2.html delete mode 100644 assignment/network/http/simple_webserver/yujin/article3.html delete mode 100644 assignment/network/http/simple_webserver/yujin/client.py delete mode 100644 assignment/network/http/simple_webserver/yujin/index.html delete mode 100644 assignment/network/http/simple_webserver/yujin/server.py delete mode 100644 "assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article1.html" delete mode 100644 "assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article2.html" delete mode 100644 "assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article3.html" delete mode 100644 "assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/index.html" delete mode 100644 "assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/server.cpp" delete mode 100644 "assignment/network/http/\354\213\261\352\270\200 \354\212\244\353\240\210\353\223\234 \352\270\260\353\260\230\354\235\230 \354\264\210\352\260\204\353\213\250 \354\240\225\354\240\201 \354\233\271\354\204\234\353\262\204 \353\247\214\353\223\244\352\270\260.md" delete mode 100644 assignment/os/thread/assign1_hwangon.py.md delete mode 100644 assignment/os/thread/assign2_seoneui/tcp_echo_client.cpp delete mode 100644 assignment/os/thread/assign2_seoneui/tcp_echo_server.cpp delete mode 100644 assignment/os/thread/assign2_seoneui/udp_echo_client.cpp diff --git a/README.md b/README.md deleted file mode 100644 index 6a6144b..0000000 --- a/README.md +++ /dev/null @@ -1,11 +0,0 @@ -### 개요 -공부하고 학습한 내용을 정리합니다. -평소 알게 모르게 넘어갔던 -지식들을 탄탄히 다지기 위한 내용들을 정리합니다. - -옵시디언을 기반으로 작성됐습니다. -clone해서 옵시디언에서 보시면 편하게 보실 수 있습니다. - -[옵시디언 링크](https://obsidian.md/) - - diff --git a/assignment/assign1_yujin.py b/assignment/assign1_yujin.py deleted file mode 100644 index 782513d..0000000 --- a/assignment/assign1_yujin.py +++ /dev/null @@ -1,22 +0,0 @@ -import time -import random -from threading import Event, Thread - -def timer(stop_event): - time.sleep(1) # n이 2일 경우 running은 1번만 출력돼야 함 (2초 실행되면 종료돼야 함으로) 그래서 1초 일부러 쉼 - m = random.randint(1, 5) - print(m) #혹시나 해서 출력 해봄 - for _ in range(m): - if stop_event.is_set(): #결국은 n초 동안해야 해서 - break - print("running..") - time.sleep(1) - -if __name__ == "__main__": - stop_event = Event() - n = int(input("Enter a number: ")) - t = Thread(target=timer, args=(stop_event,)) - t.start() - time.sleep(n) # n초 세기 - stop_event.set() - t.join() diff --git a/assignment/network/http/simple_webserver/nayoung/article1.html b/assignment/network/http/simple_webserver/nayoung/article1.html deleted file mode 100644 index 699bedf..0000000 --- a/assignment/network/http/simple_webserver/nayoung/article1.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - -

Article 1

-

Article 1 is the first article of this website.

- - diff --git a/assignment/network/http/simple_webserver/nayoung/article2.html b/assignment/network/http/simple_webserver/nayoung/article2.html deleted file mode 100644 index 436172a..0000000 --- a/assignment/network/http/simple_webserver/nayoung/article2.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - -

Article 2

-

Article 2 is the second article of this website.

- - diff --git a/assignment/network/http/simple_webserver/nayoung/article3.html b/assignment/network/http/simple_webserver/nayoung/article3.html deleted file mode 100644 index f26bd05..0000000 --- a/assignment/network/http/simple_webserver/nayoung/article3.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - -

Article 3

-

Article 3 is the third article of this website.

- - diff --git a/assignment/network/http/simple_webserver/nayoung/client.js b/assignment/network/http/simple_webserver/nayoung/client.js deleted file mode 100644 index ac4ee03..0000000 --- a/assignment/network/http/simple_webserver/nayoung/client.js +++ /dev/null @@ -1,41 +0,0 @@ -const http = require("http"); - -const request = () => { - const startTime = Date.now(); - - const options = { - hostname: "localhost", - port: 8080, - path: "/article1.html", - method: "GET", - }; - - const req = http.request(options, (res) => { - let data = ""; - - res.on("data", (chunk) => { - data += chunk; - }); - - res.on("end", () => { - const endTime = Date.now(); - const elapsedTime = endTime - startTime; - console.log(`Request completed in ${elapsedTime} milliseconds`); - }); - }); - - req.on("error", (err) => { - console.error(`Request error: ${err}`); - }); - - req.end(); -}; - -const parallelRequests = (num) => { - for (let i = 0; i < num; i++) { - request(); - } -}; - -const numRequests = 100; -parallelRequests(numRequests); diff --git a/assignment/network/http/simple_webserver/nayoung/index.html b/assignment/network/http/simple_webserver/nayoung/index.html deleted file mode 100644 index ea2e4e2..0000000 --- a/assignment/network/http/simple_webserver/nayoung/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - -

Simple Web Server

- - - - - diff --git a/assignment/network/http/simple_webserver/nayoung/server.js b/assignment/network/http/simple_webserver/nayoung/server.js deleted file mode 100644 index 161e5de..0000000 --- a/assignment/network/http/simple_webserver/nayoung/server.js +++ /dev/null @@ -1,60 +0,0 @@ -const http = require("http"); -const fs = require("fs"); -const url = require("url"); - -const HTTP_RESPONSE_TEMPLATE = (status_code, content_type, content) => { - return `HTTP/1.1 ${status_code}\nContent-Type: ${content_type}\n${content}`; -}; - -const handleRequest = (request, response) => { - const parsedUrl = url.parse(request.url); - - // random timeout - const timeout = Math.floor(Math.random() * 1000); - setTimeout(() => { - console.log(`Request for ${parsedUrl.pathname} received`); - }, timeout); - - if (request.method === "GET") { - let filePath = "." + parsedUrl.pathname; - - // "/" 경로인 경우에는 index.html로 설정 - if (filePath === "./") { - filePath = "./index.html"; - } - - fs.readFile(filePath, (err, data) => { - if (err) { - const errMessage = HTTP_RESPONSE_TEMPLATE( - 500, - "text/plain", - "Server Error" - ); - response.writeHead(500); - response.end(errMessage); - console.log(`Error: ${err}`); - return; - } - - const responseMessage = HTTP_RESPONSE_TEMPLATE(200, "text/html", data); - response.writeHead(200); - response.end(responseMessage); - console.log(`File served: ${filePath}`); - }); - } else { - const errMessage = HTTP_RESPONSE_TEMPLATE( - 405, - "text/plain", - "Method Not Allowed" - ); - response.writeHead(405); - response.end(errMessage); - console.log(`Error: Method Not Allowed - ${request.method}`); - } -}; - -const server = http.createServer(handleRequest); - -server.listen(8080, () => { - console.log("Server is running on port 8080"); -}); diff --git a/assignment/network/http/simple_webserver/ym/homework_client.py b/assignment/network/http/simple_webserver/ym/homework_client.py deleted file mode 100644 index 30660c0..0000000 --- a/assignment/network/http/simple_webserver/ym/homework_client.py +++ /dev/null @@ -1,50 +0,0 @@ -import socket -import webbrowser -import tempfile -import time -import threading - - -def make_http_request_and_open_response(host, port, request_path): - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: - s.connect((host, port)) - request = f"GET {request_path} HTTP/1.1\r\nHost: {host}\r\n\r\n" - - start_time = time.time() - s.send(request.encode('utf-8')) - - response = s.recv(4096).decode('utf-8') - end_time = time.time() - - response_time = end_time - start_time - print(f"응답 시간: {response_time:.4f}초") - - header_end_index = response.find('\r\n\r\n') + 4 - html_content = response[header_end_index:] - - # HTML 콘텐츠를 임시 파일에 저장하고 웹브라우저에서 열기 - with tempfile.NamedTemporaryFile(delete=False, suffix='.html') as temp_file: - temp_file.write(html_content.encode('utf-8')) - temp_file_path = temp_file.name - - webbrowser.open(f'file://{temp_file_path}') - - -def make_requests_concurrently(host, port, request_path, num_requests): - threads = [] - for _ in range(num_requests): - thread = threading.Thread(target=make_http_request_and_open_response, args=(host, port, request_path)) - threads.append(thread) - thread.start() - - for thread in threads: - thread.join() # 모든 스레드가 완료될 때까지 기다림 - - -if __name__ == "__main__": - host = "127.0.0.1" - port = 8000 - request_path = "/" - num_requests = 100 # 예시로 요청 수를 5개로 줄임 - - make_requests_concurrently(host, port, request_path, num_requests) diff --git a/assignment/network/http/simple_webserver/ym/homework_server.py b/assignment/network/http/simple_webserver/ym/homework_server.py deleted file mode 100644 index 1e6c660..0000000 --- a/assignment/network/http/simple_webserver/ym/homework_server.py +++ /dev/null @@ -1,84 +0,0 @@ -import asyncio -import socket -import time - -# 서버 설정 -host = "127.0.0.1" # 서버의 IP 주소 또는 도메인 이름 -port = 8000 # 포트 번호 - -# 기본 HTML 파일 경로 -base_html_path = "./src" - -# 서버 소켓 생성 -server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -server_socket.bind((host, port)) -server_socket.listen(5) -server_socket.setblocking(False) - -print(f"서버가 {host}:{port}에서 대기 중입니다...") - -# 요청 처리 시간 저장을 위한 리스트 -request_times = [] - -async def task(client_socket): - start_time = time.time() # 요청 처리 시작 시간 - - try: - # 클라이언트 요청 수신 - event_request = client_socket.recv(1024).decode("utf-8") - # 요청된 첫 번째 줄 파싱 (예: "GET /article1.html HTTP/1.1") - first_line = event_request.split("\n")[0] - # URL 추출 - url = first_line.split(" ")[1] - - # 루트("/") 요청을 "index.html"로 매핑 - if url == "/": - url = "/index.html" - - # 요청된 파일 경로 생성 - file_path = base_html_path + url - - # 파일 내용 가져오기 - content = get_file_content(file_path) - if content: - response = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n" + content - else: - # 파일이 없을 때 404 응답 - response = "HTTP/1.1 404 Not Found\n\n

404 Not Found

" - - client_socket.send(response.encode("utf-8")) - - except Exception as e: - print(f"오류 발생: {e}") - error_response = "HTTP/1.1 500 Internal Server Error\n\nInternal Server Error" - client_socket.send(error_response.encode("utf-8")) - finally: - end_time = time.time() # 요청 처리 종료 시간 - request_times.append(end_time - start_time) # 처리 시간 저장 - average_time = sum(request_times) / len(request_times) # 평균 요청 처리 시간 계산 - print(f"평균 요청 처리 시간: {average_time:.4f}초") - client_socket.close() - -async def handle_client(client_socket, client_address): - print(f"클라이언트 {client_address}가 연결되었습니다.") - await task(client_socket) - - -def get_file_content(filename): - # 파일반환 - try: - with open(filename, "r", encoding="utf-8") as file: - return file.read() - except FileNotFoundError: - return None - -async def main(): - print("시작") - while True: - loop = asyncio.get_running_loop() - - while True: - client_socket, client_address = await loop.sock_accept(server_socket) - asyncio.create_task(handle_client(client_socket, client_address)) - -asyncio.run(main()) diff --git a/assignment/network/http/simple_webserver/ym/src/article1.html b/assignment/network/http/simple_webserver/ym/src/article1.html deleted file mode 100644 index 5a3b852..0000000 --- a/assignment/network/http/simple_webserver/ym/src/article1.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - 메인 페이지 - - - -
-

환영합니다!

-

네트워크 html 서버 숙제

-
-
-
-

소개

-

이 사이트는 네트워크를 공부하는 스터디입니다. 과제용 웹페이지입니다.

-
-
-

이미지

- Placeholder Image -

위 이미지는 placeholder.com에서 제공하는 샘플 이미지입니다.

-
-
-

더 알아보기

-

HTML, CSS, JavaScript 등 웹 개발에 대해 더 배우고 싶다면 MDN Web Docs를 방문해 보세요.

-
-
- - - diff --git a/assignment/network/http/simple_webserver/ym/src/article2.html b/assignment/network/http/simple_webserver/ym/src/article2.html deleted file mode 100644 index 861e5f2..0000000 --- a/assignment/network/http/simple_webserver/ym/src/article2.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - article2 - - - - - \ No newline at end of file diff --git a/assignment/network/http/simple_webserver/ym/src/article3.html b/assignment/network/http/simple_webserver/ym/src/article3.html deleted file mode 100644 index 65bb261..0000000 --- a/assignment/network/http/simple_webserver/ym/src/article3.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - article3 - - - - - \ No newline at end of file diff --git a/assignment/network/http/simple_webserver/ym/src/index.html b/assignment/network/http/simple_webserver/ym/src/index.html deleted file mode 100644 index d3b417c..0000000 --- a/assignment/network/http/simple_webserver/ym/src/index.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - 메인 페이지 - - - -
-

환영합니다!

-

네트워크 html 서버 숙제

-
-
- - -
- - - -
-
- - - - - diff --git a/assignment/network/http/simple_webserver/yujin/article1.html b/assignment/network/http/simple_webserver/yujin/article1.html deleted file mode 100644 index e3adb60..0000000 --- a/assignment/network/http/simple_webserver/yujin/article1.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - 게시글 1 - - -

게시글 1

-

이곳에는 article1에 대한 내용이 포함됩니다. 자유롭게 내용을 추가하세요.

- 홈으로 돌아가기 - - diff --git a/assignment/network/http/simple_webserver/yujin/article2.html b/assignment/network/http/simple_webserver/yujin/article2.html deleted file mode 100644 index 1d7c125..0000000 --- a/assignment/network/http/simple_webserver/yujin/article2.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - 게시글 2 - - -

게시글 2

-

이곳에는 article1에 대한 내용이 포함됩니다. 자유롭게 내용을 추가하세요.

- 홈으로 돌아가기 - - diff --git a/assignment/network/http/simple_webserver/yujin/article3.html b/assignment/network/http/simple_webserver/yujin/article3.html deleted file mode 100644 index f0d5998..0000000 --- a/assignment/network/http/simple_webserver/yujin/article3.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - 게시글 3 - - -

게시글 3

-

이곳에는 article1에 대한 내용이 포함됩니다. 자유롭게 내용을 추가하세요.

- 홈으로 돌아가기 - - diff --git a/assignment/network/http/simple_webserver/yujin/client.py b/assignment/network/http/simple_webserver/yujin/client.py deleted file mode 100644 index cf89f95..0000000 --- a/assignment/network/http/simple_webserver/yujin/client.py +++ /dev/null @@ -1,32 +0,0 @@ -import requests -import time -# 동시성 실행을 위한 라이브러리로, 여러 스레드에서 함수를 병렬로 실행할 수 있게함 -from concurrent.futures import ThreadPoolExecutor - -# HTTP GET 요청을 보내고, 응답의 상태 코드를 반환하는 함수 -def getStatusCode(url): - with requests.get(url) as response: - return response.status_code - -def main(): - url = "http://127.0.0.1:8080/index.html" - with ThreadPoolExecutor(max_workers=100) as executor: - - # 얘를 안쓰고 싶음... - # 최대 100개의 스레드를 가진 ThreadPoolExecutor를 생성 - start_time = time.time() # 요청 시작 시간 기록 - - # executor.submit: 100개의 요청을 병렬로 보냄, getStatusCode 함수를 100번 호출 - # futures 리스트에 저장 - futures = [executor.submit(getStatusCode, url) for _ in range(100)] - # futures 리스트에 저장된 모든 future 객체의 결과를 기다리고, 각각의 결과(Status code)를 results 리스트에 저장 - results = [future.result() for future in futures] - end_time = time.time() - - # 총 시간, 평균 요청 시간, 모든 요청의 상태 코드 출력 - print(f"100 requests completed in {end_time - start_time} seconds") - print(f"Average request time: {(end_time - start_time) / 100} seconds") - print(f"Status codes: {results}") - -if __name__ == "__main__": - main() diff --git a/assignment/network/http/simple_webserver/yujin/index.html b/assignment/network/http/simple_webserver/yujin/index.html deleted file mode 100644 index fbb4313..0000000 --- a/assignment/network/http/simple_webserver/yujin/index.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - HI-JIN2 - - -

안녕하세요! 유진입니다.

-

메타몽을 좋아하는 개발자입니다. 롤모델은 메타몽입니다.

- - - diff --git a/assignment/network/http/simple_webserver/yujin/server.py b/assignment/network/http/simple_webserver/yujin/server.py deleted file mode 100644 index 256bcb7..0000000 --- a/assignment/network/http/simple_webserver/yujin/server.py +++ /dev/null @@ -1,54 +0,0 @@ -import asyncio -import random -import time - -async def work(reader, writer): - request_line = await reader.readline() - request_line = request_line.decode('utf-8').strip() - print(f"Received request: {request_line}") - - try: - method, path, _ = request_line.split() - print(f"{method, path}") - - #GET 아닐 때 예외처리 - if method != 'GET': - raise ValueError("Only GET requests are supported") - - # 요청된 파일 경로 설정 - filepath = f'{path}' # 루트 폴더를 현재 디렉터리로 가정 - if path[0] == '/': - # 얘가 상대경로를 못찾네.. - filepath = 'assignment/network/http/simple_webserver/yujin/index.html' - - # 파일 읽기 - with open(filepath, 'rb') as f: - content = f.read() - - # 랜덤 대기 - await asyncio.sleep(random.randint(1, 3)) - - # 응답 전송 - writer.write(b"HTTP/1.1 200 OK\r\n") - writer.write(b"Content-Type: text/html\r\n") - writer.write(b"\r\n") - writer.write(content) - - #예외처리 다 500 - except Exception as e: - writer.write(b"HTTP/1.1 500 Internal Server Error\r\n") - writer.write(b"Content-Type: text/html\r\n") - writer.write(b"\r\n") - writer.write(b"Server Error") - print(f"Error: {e}") - - finally: - await writer.drain() - writer.close() - -async def main(): - server = await asyncio.start_server(work, '127.0.0.1', 8080) - print(f"Serving on {server.sockets[0].getsockname()}") - await server.serve_forever() - -asyncio.run(main()) diff --git "a/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article1.html" "b/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article1.html" deleted file mode 100644 index afac0e1..0000000 --- "a/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article1.html" +++ /dev/null @@ -1,15 +0,0 @@ - - - - - article1 - - - - - - article1 - - - - \ No newline at end of file diff --git "a/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article2.html" "b/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article2.html" deleted file mode 100644 index 782dd5b..0000000 --- "a/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article2.html" +++ /dev/null @@ -1,15 +0,0 @@ - - - - - article2 - - - - - article2 - - - - - \ No newline at end of file diff --git "a/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article3.html" "b/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article3.html" deleted file mode 100644 index 958af2a..0000000 --- "a/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/article3.html" +++ /dev/null @@ -1,15 +0,0 @@ - - - - - article3 - - - - - article3 - - - - - \ No newline at end of file diff --git "a/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/index.html" "b/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/index.html" deleted file mode 100644 index c354a77..0000000 --- "a/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/index.html" +++ /dev/null @@ -1,18 +0,0 @@ - - - - - 메인 페이지 - - - - - article1 - article2 - article3 - - - - - - \ No newline at end of file diff --git "a/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/server.cpp" "b/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/server.cpp" deleted file mode 100644 index 605ecea..0000000 --- "a/assignment/network/http/simple_webserver/\354\247\200\354\204\240\354\235\230/server.cpp" +++ /dev/null @@ -1,178 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -//int PORT = 8080; -const int BUFFER_SIZE = 1024; - -#define HEADER_FMT "HTTP/1.1 %d %s\r\nContent-Length: %ld\r\nContent-Type: %s\r\n\r\n" -#define NOT_FOUND_CONTENT "404 Not Found" -#define SERVER_ERROR_CONTENT "500 Internal Server Error" - -using namespace std; - -void httpHandler(int acceptSocket); -void fill_header(char *header, int status, long len, char *type); -void find_mime(char *ct_type, char *uri); -void handle_404(int acceptSocket); -void handle_500(int acceptSocket); - -int main(int argc, char **argv){ - struct sockaddr_in remote_sin; - int PORT, pid; - - if(argc < 2){ - cout<<"Usage"< 0){ //파일에서 데이터를 읽어와서 클라이언트에게 전송하는데, 파일의 내용을 버퍼 사이즈만큼 읽고 읽은 데이터를 클라이언트에게 전송 - write(acceptSocket, buf, cnt); - } - -} - -//http 해더 형식 지정 함수 -void fill_header(char *header, int status, long len, char *type){ - char status_text[40]; //http응답 상태 코드에 해당하는 텍스트 저장 - switch(status){ - case 200: - strcpy(status_text,"OK"); //status_text에 적절한 텍스트 복사 - break; - case 404: - strcpy(status_text,"NOT FOUND"); - break; - case 500: - default : - strcpy(status_text,"Internet Server Error"); - break; - } - sprintf(header, HEADER_FMT, status, status_text, len, type); //header문자열에 http응답 헤더를 형식화해서 삽입 -} - -//uri에서 MIME 타입을 찾는 함수 -void find_mime(char *ct_type, char *uri){ - char *ext = strrchr(uri, '.'); - if(!strcmp(ext, ".html")){ - strcpy(ct_type, "text/html"); - } -} - -//404 에러 처리 -void handle_404(int acceptSocket){ - char header[BUFFER_SIZE]; - fill_header(header, 404, sizeof(NOT_FOUND_CONTENT), "text/html"); - write(acceptSocket, header, strlen(header)); -} - -//500 에러 처리 -void handle_500(int acceptSocket){ - char header[BUFFER_SIZE]; - fill_header(header, 500, sizeof(SERVER_ERROR_CONTENT), "text/html"); - write(acceptSocket, header, strlen(header)); -} \ No newline at end of file diff --git "a/assignment/network/http/\354\213\261\352\270\200 \354\212\244\353\240\210\353\223\234 \352\270\260\353\260\230\354\235\230 \354\264\210\352\260\204\353\213\250 \354\240\225\354\240\201 \354\233\271\354\204\234\353\262\204 \353\247\214\353\223\244\352\270\260.md" "b/assignment/network/http/\354\213\261\352\270\200 \354\212\244\353\240\210\353\223\234 \352\270\260\353\260\230\354\235\230 \354\264\210\352\260\204\353\213\250 \354\240\225\354\240\201 \354\233\271\354\204\234\353\262\204 \353\247\214\353\223\244\352\270\260.md" deleted file mode 100644 index 23b4822..0000000 --- "a/assignment/network/http/\354\213\261\352\270\200 \354\212\244\353\240\210\353\223\234 \352\270\260\353\260\230\354\235\230 \354\264\210\352\260\204\353\213\250 \354\240\225\354\240\201 \354\233\271\354\204\234\353\262\204 \353\247\214\353\223\244\352\270\260.md" +++ /dev/null @@ -1,58 +0,0 @@ - -#### 주요 기능 - -1.  서버는 유저로부터 적절한 HTTP GET 요청을 수신할 경우 적절한 파일을 반환한다. - - * 적절한 요청이란 GET 요청이며, 알맞은 URL이 전달된 경우를 말한다. 서버는 요청이 올바른지 확인해야 하며 요청이 올바르지 않을 경우 이에 알맞은 에러 코드를 반환해야 한다. - - * 잘못된 요청의 경우 별도의 처리를 추가 진행해도 괜찮으나 (가산점 존재) 일관적으로 500 번 상태코드와 servcer error라는 HTTP 메시지를 반환하게 처리한다. (에러 페이지용 HTML을 별도 작성할 필요는 없다) - - -2. 서버는 요청 수신시 랜덤한 시간을 기다리고 요청된 파일을 반환한다. (1 ~ 3초) - - * 각 파일들은 모두 미리 생성돼 웹서버의 루트 폴더에 저장돼 있다. - - * 서버가 소유하고 있는 파일은 아래와 같다. - * index.html: 사이트의 얼굴이 되는 페이지로 자기 소개글과 다른 게시글 페이지로 이동 할 수 있는 링크가 존재한다. (레이아웃 자유) - * article1.html: 게시글 페이지로 article1이라는 문구가 포함된 아무 글이나 존재하면 된다. (레이아웃 자유) - * article2.html: 1과 동일 - * article3.html: 1과 동일 - - - -4. 서버는 100명의 클라이언트가 동시 다발적으로 요청하는 상황이 발생하더라도 각 클라이언트 별 평균 처리시간은 3초가 넘으면 안된다. - - * 이때 평균 요청 시간을 측정하는 별도의 클라이언트 프로그램 코드를 작성해 테스트 하는 것이 좋다. - - * 클라이언트 테스트 코드는 순간적으로 100개의 요청을 보내 각 요청별 평균 소요 시간을 측정하면 된다. - - * 요청 테스트는 URL 중 임의로 한곳을 골라 진행하면 된다. - - -5. 서버 코드는 되도록 이벤트 루프를 포함한 싱글 스레드 비동기-논블락킹을 활용해 구현한다. (수업 시간에 멀티 쓰레드 예제를 진행할 예정) - -6. 서버는 자신에게 들어온 모든 HTTP 요청을 터미널에 로깅한다. - -#### 제약 사항 - -* 외부 라이브러리의 도움 없이 최대한 언어 자체의 기능만으로 작업할 것. -* 언어 제한은 크게 없으나 모두가 생소한 언어일 경우 상세히 설명해야 함 -* 과제로 제출된 코드는 다같이 리뷰 할 예정이니 되도록 주석을 달아주는 편이 좋음 -* 실제로 평균 3초를 만족하는지 확인할 예정이므로 측정 방법을 되도록 간단한 방법으로 구현해주면 - -#### 제출방식 - -* 깃 레포지토리의 assginment/network/http/simple_webserver/[본인이름]의 폴더 생성 -* 이후 해당 폴더 위치에 **HTTP 서버 코드 및 클라이언트 코드 첨부**해서 PR 제출 - -### 전송 예시 - -```http -GET /index.html HTTP/1.1 -Host: www.example.com -``` - -### 참고할 만한 곳 - -* https://developer.mozilla.org/ko/docs/Web/HTTP/Messages (HTTP 메시지) -* https://inpa.tistory.com/entry/LINUX-%F0%9F%93%9A-CURL-%EB%AA%85%EB%A0%B9%EC%96%B4-%EC%82%AC%EC%9A%A9%EB%B2%95-%EB%8B%A4%EC%96%91%ED%95%9C-%EC%98%88%EC%A0%9C%EB%A1%9C-%EC%A0%95%EB%A6%AC (CURL) \ No newline at end of file diff --git a/assignment/os/thread/assign1_hwangon.py.md b/assignment/os/thread/assign1_hwangon.py.md deleted file mode 100644 index 53ab47b..0000000 --- a/assignment/os/thread/assign1_hwangon.py.md +++ /dev/null @@ -1,55 +0,0 @@ -```go -// 비동기-논블라킹 -package main - -import ( - "fmt" - "time") - -// 계속 돌다가 n초 지나면 죽어야함 -func printRunning(done chan bool) { - for { - // 1초마다 출력 - time.Sleep(time.Second) - fmt.Println("Running...") - - // select로 1초마다 done 채널 확인하기 - select { - case <-done: - return - default: - } - } -} - -func timeOut(seconds int, done chan bool) { - time.Sleep(time.Duration(seconds) * time.Second) - // n초 후 done을 true로 변경 - done <- true -} - -func runAsync() { - var n int - fmt.Print("Enter the value of n: ") - fmt.Scan(&n) - - // 고루틴을 위한 done 채널 만들기 - done := make(chan bool) - - // 고루틴으로 비동기 실행 - go printRunning(done) - - // 고루틴으로 비동기 실행 - go timeOut(n, done) - - // n초 후(done이 true가 되면) 작업 종료 - select { - case <-done: - fmt.Println("Task completed.") - } -} - -func main() { - runAsync() -} -``` \ No newline at end of file diff --git a/assignment/os/thread/assign2_seoneui/tcp_echo_client.cpp b/assignment/os/thread/assign2_seoneui/tcp_echo_client.cpp deleted file mode 100644 index 98af713..0000000 --- a/assignment/os/thread/assign2_seoneui/tcp_echo_client.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include -#include -#include -#include -#include - -const char* SERVER_IP = "127.0.0.1"; -const int PORT = 8080; -const int BUFFER_SIZE = 1024; - -using namespace std; - -int main() { - // 소켓 생성 - int clientSocket = socket(AF_INET, SOCK_STREAM, 0); - if (clientSocket == -1) { - std::cerr << "소켓 생성에 실패했습니다." << std::endl; - return 1; - } - - // 서버 주소 설정 - sockaddr_in serverAddress; - serverAddress.sin_family = AF_INET; - serverAddress.sin_port = htons(PORT); // 서버의 포트 번호 - serverAddress.sin_addr.s_addr = inet_addr(SERVER_IP); // 서버의 IP 주소 - - // 서버에 연결 - if (connect(clientSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) == -1) { - cerr << "서버에 연결할 수 없습니다." << endl; - close(clientSocket); - return 1; - } - - cout << "서버에 연결되었습니다." << endl; - - // 통신 루프 - while (true) { - // 사용자로부터 메시지 입력 - cout << "보내기(또는 'bye' 입력하여 종료): "; - string message; - getline(cin, message); - - // 서버에 메시지 전송 - send(clientSocket, message.c_str(), message.size(), 0); - - // 서버로부터 메시지 수신 - char buffer[BUFFER_SIZE]; - ssize_t bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - if (bytesRead <= 0) { - cerr << "데이터 수신에 실패했습니다." << endl; - break; - } - - buffer[bytesRead] = '\0'; - cout << "서버: " << buffer << endl; - - // 사용자가 'bye'를 입력하면 루프 종료 - if (message == "bye") { - break; - } - } - - // 소켓 종료 - close(clientSocket); - - return 0; -} diff --git a/assignment/os/thread/assign2_seoneui/tcp_echo_server.cpp b/assignment/os/thread/assign2_seoneui/tcp_echo_server.cpp deleted file mode 100644 index a9f2932..0000000 --- a/assignment/os/thread/assign2_seoneui/tcp_echo_server.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include -#include -#include -#include -#include - -const int PORT = 8080; -const int BUFFER_SIZE = 1024; - -using namespace std; - -int main() { - // 소켓 생성 - int serverSocket = socket(AF_INET, SOCK_STREAM, 0); - if (serverSocket == -1) { - cerr << "소켓 생성에 실패했습니다." << endl; - return 1; - } - - // 서버 주소 설정 - sockaddr_in serverAddress; - serverAddress.sin_family = AF_INET; - serverAddress.sin_port = htons(PORT); // 서버의 포트 번호 - serverAddress.sin_addr.s_addr = INADDR_ANY; - - // 소켓 바인딩 - if (bind(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) == -1) { - cerr << "바인딩에 실패했습니다." << endl; - close(serverSocket); - return 1; - } - - // 소켓 리스닝 - if (listen(serverSocket, 5) == -1) { - cerr << "리스닝에 실패했습니다." << endl; - close(serverSocket); - return 1; - } - - cout << "연결 대기중..." << endl; - - while (true) { - // 클라이언트 연결 수락 - sockaddr_in clientAddress; - socklen_t clientAddressLength = sizeof(clientAddress); - int clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddress, &clientAddressLength); - - if (clientSocket == -1) { - cerr << "연결 수락에 실패했습니다." << endl; - close(serverSocket); - return 1; - } - - cout << "연결되었습니다." << endl; - - // 통신 루프 - while (true) { - // 클라이언트로부터 메시지 수신 - char buffer[BUFFER_SIZE]; - ssize_t bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); - - if (bytesRead <= 0) { - cerr << "데이터 수신에 실패했습니다." << endl; - break; - } - - buffer[bytesRead] = '\0'; - - cout << "클라이언트: " << buffer << endl; - - // 클라이언트가 "bye"를 입력했을 때 종료 - if (strcmp(buffer, "bye") == 0) { - // 서버에서 클라이언트로 "bye" 전송 - send(clientSocket, "bye", 3, 0); - close(clientSocket); - break; // 루프를 종료하고 다음 클라이언트 연결을 대기 - } - - // 클라이언트에 메시지 전송 - send(clientSocket, buffer, bytesRead, 0); - } - - cout << "연결 대기중입니다..." << endl; - } - - // 소켓 종료 (실행되지 않음) - close(serverSocket); - - return 0; -} diff --git a/assignment/os/thread/assign2_seoneui/udp_echo_client.cpp b/assignment/os/thread/assign2_seoneui/udp_echo_client.cpp deleted file mode 100644 index 93617e9..0000000 --- a/assignment/os/thread/assign2_seoneui/udp_echo_client.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include -#include -#include -#include -#include - -const char* SERVER_IP = "127.0.0.1"; -const int PORT = 8080; -const int BUFFER_SIZE = 1024; - -using namespace std; - -int main() { - // 소켓 생성 - int clientSocket = socket(AF_INET, SOCK_DGRAM, 0); - if (clientSocket == -1) { - cerr << "소켓 생성에 실패했습니다." << endl; - return 1; - } - - // 서버 주소 설정 - sockaddr_in serverAddress; - serverAddress.sin_family = AF_INET; - serverAddress.sin_port = htons(PORT); // 서버의 포트 번호 - serverAddress.sin_addr.s_addr = inet_addr(SERVER_IP); // 서버의 IP 주소 - - while (true) { - // 사용자로부터 메시지 입력 - cout << "전송할 메시지 입력 (또는 'bye' 입력하여 종료): "; - string message; - getline(cin, message); - - // 서버에 메시지 전송 - ssize_t bytesSent = sendto(clientSocket, message.c_str(), message.size(), 0, - (struct sockaddr *)&serverAddress, sizeof(serverAddress)); - - if (bytesSent == -1) { - std::cerr << "데이터 전송에 실패했습니다." << std::endl; - break; - } - - // 서버로부터 메시지 수신 - char buffer[BUFFER_SIZE]; - sockaddr_in serverResponseAddress; - socklen_t serverResponseAddressLength = sizeof(serverResponseAddress); - - ssize_t bytesRead = recvfrom(clientSocket, buffer, sizeof(buffer), 0, - (struct sockaddr *)&serverResponseAddress, &serverResponseAddressLength); - - if (bytesRead == -1) { - cerr << "데이터 수신에 실패했습니다." << endl; - break; - } - - buffer[bytesRead] = '\0'; - - cout << "서버에서의 응답: " << buffer << endl; - - // 'bye'를 입력하면 클라이언트 종료 - if (message == "bye") { - break; - } - } - - // 소켓 종료 - close(clientSocket); - - return 0; -} diff --git "a/os/\353\217\231\352\270\260\354\231\200 \353\271\204\353\217\231\352\270\260 (Blocking, None-Blocking).md" "b/os/\353\217\231\352\270\260\354\231\200 \353\271\204\353\217\231\352\270\260 (Blocking, None-Blocking).md" index 623bf56..90e3d72 100644 --- "a/os/\353\217\231\352\270\260\354\231\200 \353\271\204\353\217\231\352\270\260 (Blocking, None-Blocking).md" +++ "b/os/\353\217\231\352\270\260\354\231\200 \353\271\204\353\217\231\352\270\260 (Blocking, None-Blocking).md" @@ -95,7 +95,7 @@ int sync_none_block_test(int fd, int fd2, char *buffer, char *buffer2) 위는 동기-논블락킹 방식의 예시이다. 함수의 호출부가 응답 결과를 관리하며 **논 블락킹이기 때문에 IO로 인해 실행 흐름이 막히지 않는다.** 또한 **파일을 전부 읽었다는 것을 확인하기 위해 while문 내부에서 busy-waiting이 발생하는 것을 볼 수 있다.** 흥미로운 부분은 늦게 실행된 2번째 none-block-read 함수가 더 빨리 종료 될 수 있다는 점이다. 만약 2번째로 읽는 파일의 크기가 더욱 작을 경우 더 빨리 종료될 수 있다. > [!info] -> **동기만으로는 완료순서를 보장하지 못한다.** +> **블록킹이 되는 동기는 확실한 실행 순서를 보장합니다. 하지만 블록킹이 되지 않는 동기는 실행순서를 보장하지 못합니다.** ___ ### Async