컴공 일기278
게시글 주소: https://orbi.kr/00073281944
가산점을 주는 네트워크 과제입니다.
4장 이내 11pt 설계보고서, 소스코드 원본을 제출해야 하며
연구실에서 1:1 인터뷰를 통해 데모 실행 및 설명을 해야 합니다.
TCP/IP 통신기반의 공유 문서 작성 및 읽기 프로그램입니다.
소켓 프로그래밍과 시스템 프로그래밍에서 자주 사용되는 기법을 적절히 조화시켜야 하는데 가장 핵심적인 기능 중 하나는, write 명령이 클라이언트로부터 왔을 때, 서버는 한줄씩 데이터를 받아들이는 겁니다. 이걸 구현하는 것이 이 과제의 핵심 중 하나가 아닌가 생각하네요.
소켓의 본질을 알고 있어야, 이 기능을 구현할 수 있거든요.
소켓의 본질은 파일입니다. 파일은 데이터 단위가 Stream인데,
이 스트림은 시작은 확실히 정해져 있지만, 끝이 어딘지 확실하지 않다는 특징을 갖고 있습니다. 그렇기 때문에 ‘줄 입력‘이 여기서 종료되었다는 판단을 아무런 정보가 없다면 서버는 할 수 없죠.
따라서 적절한 시그널을 주고받는 프로토콜 절차가 있어야 합니다.
인터뷰에서 시그널을 주고받음으로써 줄의 끝이 어디까지인지 서버가 알도록 한다는 말씀을 드렸을 때, 인터뷰 평가 사항에 무엇인가를 막 적고 계시더라구요. 그때 조금 확실히 알게된 것 같습니다.
과제의 의도가 결국 ‘소켓’이 무엇인지 정확히 알고 있느냐라는 걸요.. 사실 이 얘기는 네트워크 이론과 운영체제론을 알고 있어야 이해할 수 있을 겁니다. 조금 더 다듬어서 비동기 입출력까지 지원하는 서버를 한번 만들어 보려구요. 설계 구조를 완전히 바꿔야 겠지만, 오랜만에 아주 재미있는 프로젝트를 하게 되어서 이 내용물은 깃허브에 올려 볼 것 같습니다.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_DOCS 100
#define MAX_SECTIONS 10
#define MAX_TITLE 64
#define MAX_LINE 256
#define MAX_LINES 10
#define BUF_SIZE 1024
typedef struct {
char title[MAX_TITLE];
char section_titles[MAX_SECTIONS][MAX_TITLE];
char section_contents[MAX_SECTIONS][MAX_LINES][MAX_LINE];
int section_line_count[MAX_SECTIONS];
int section_count;
} Document;
typedef struct WriteRequest {
int client_sock;
int estimated_lines;
struct WriteRequest *next;
} WriteRequest;
Document docs[MAX_DOCS];
int doc_count = 0;
pthread_mutex_t docs_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t section_mutex[MAX_DOCS][MAX_SECTIONS];
pthread_cond_t section_cond[MAX_DOCS][MAX_SECTIONS];
int section_writing[MAX_DOCS][MAX_SECTIONS] = {{0}};
WriteRequest *section_queue[MAX_DOCS][MAX_SECTIONS] = {{{0}}};
pthread_mutex_t section_queue_mutex[MAX_DOCS][MAX_SECTIONS];
pthread_cond_t section_queue_cond[MAX_DOCS][MAX_SECTIONS];
void send_all(int sock, const char *msg) {
send(sock, msg, strlen(msg), 0);
}
Document* find_doc(const char* title) {
for (int i = 0; i < doc_count; ++i) {
if (strcmp(docs[i].title, title) == 0)
return &docs[i];
}
return NULL;
}
ssize_t read_line(int sock, char *buf, size_t max_len) {
size_t i = 0;
char ch;
while (i < max_len - 1) {
ssize_t n = recv(sock, &ch, 1, 0);
if (n <= 0) break;
if (ch == '\n') break;
buf[i++] = ch;
}
buf[i] = '\0';
return i;
}
void parse_command(const char* input, char* args[], int* argc) {
*argc = 0;
const char* p = input;
while (*p) {
while (*p == ' ' || *p == '\t') p++;
if (*p == '"') {
p++;
const char* start = p;
while (*p && *p != '"') p++;
int len = p - start;
args[*argc] = malloc(len + 1);
strncpy(args[*argc], start, len);
args[*argc][len] = '\0';
(*argc)++;
if (*p == '"') p++;
} else {
const char* start = p;
while (*p && *p != ' ' && *p != '\t' && *p != '\n') p++;
int len = p - start;
args[*argc] = malloc(len + 1);
strncpy(args[*argc], start, len);
args[*argc][len] = '\0';
(*argc)++;
}
}
}
void* client_handler(void* arg);
int main(int argc, char* argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <IP> <Port>\n", argv[0]);
exit(1);
}
for (int i = 0; i < MAX_DOCS; ++i)
for (int j = 0; j < MAX_SECTIONS; ++j) {
pthread_mutex_init(§ion_mutex[i][j], NULL);
pthread_cond_init(§ion_cond[i][j], NULL);
pthread_mutex_init(§ion_queue_mutex[i][j], NULL);
pthread_cond_init(§ion_queue_cond[i][j], NULL);
}
int server_sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr, client_addr;
socklen_t addrlen = sizeof(client_addr);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[2]));
inet_pton(AF_INET, argv[1], &server_addr.sin_addr);
bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
listen(server_sock, 10);
printf("[Server] Listening on %s:%s\n", argv[1], argv[2]);
while (1) {
int *client_sock = malloc(sizeof(int));
*client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &addrlen);
pthread_t tid;
pthread_create(&tid, NULL, client_handler, client_sock);
pthread_detach(tid);
}
close(server_sock);
return 0;
}
void* client_handler(void* arg) {
int client_sock = *(int*)arg;
free(arg);
char buf[BUF_SIZE];
char* args[64];
int argc;
while (1) {
memset(buf, 0, sizeof(buf));
if (read_line(client_sock, buf, sizeof(buf)) <= 0) break;
parse_command(buf, args, &argc);
if (argc == 0) continue;
if (strcmp(args[0], "create") == 0) {
pthread_mutex_lock(&docs_mutex);
if (argc < 3 || doc_count >= MAX_DOCS) {
pthread_mutex_unlock(&docs_mutex);
send_all(client_sock, "[Error] Invalid create command.\n");
continue;
}
if (find_doc(args[1])) {
pthread_mutex_unlock(&docs_mutex);
send_all(client_sock, "[Error] Document already exists.\n");
continue;
}
int section_count = atoi(args[2]);
if (section_count <= 0 || section_count > MAX_SECTIONS || argc != 3 + section_count) {
pthread_mutex_unlock(&docs_mutex);
send_all(client_sock, "[Error] Invalid section count or titles.\n");
continue;
}
strcpy(docs[doc_count].title, args[1]);
docs[doc_count].section_count = section_count;
for (int i = 0; i < section_count; ++i) {
strcpy(docs[doc_count].section_titles[i], args[3 + i]);
docs[doc_count].section_line_count[i] = 0;
}
++doc_count;
pthread_mutex_unlock(&docs_mutex);
send_all(client_sock, "[OK] Document created.\n");
}
else if (strcmp(args[0], "write") == 0) {
if (argc < 3) {
send_all(client_sock, "[Error] Invalid write command.\n");
continue;
}
pthread_mutex_lock(&docs_mutex);
Document* doc = find_doc(args[1]);
if (!doc) {
pthread_mutex_unlock(&docs_mutex);
send_all(client_sock, "[Error] Document not found.\n");
continue;
}
int section_idx = -1;
for (int i = 0; i < doc->section_count; ++i)
if (strcmp(doc->section_titles[i], args[2]) == 0) {
section_idx = i;
break;
}
if (section_idx == -1) {
pthread_mutex_unlock(&docs_mutex);
send_all(client_sock, "[Error] Section not found.\n");
continue;
}
int doc_idx = doc - docs;
pthread_mutex_unlock(&docs_mutex);
send_all(client_sock, "[OK] You can start writing. Send <END> to finish.\n>> ");
int line_count = 0;
char line[MAX_LINE];
char temp_lines[MAX_LINES][MAX_LINE];
while (1) {
if (read_line(client_sock, line, sizeof(line)) <= 0) break;
if (strcmp(line, "<END>") == 0) break;
if (line_count < MAX_LINES)
strncpy(temp_lines[line_count++], line, MAX_LINE - 1);
send_all(client_sock, ">> ");
}
WriteRequest *req = malloc(sizeof(WriteRequest));
req->client_sock = client_sock;
req->estimated_lines = line_count;
req->next = NULL;
pthread_mutex_lock(§ion_queue_mutex[doc_idx][section_idx]);
if (!section_queue[doc_idx][section_idx] || line_count < section_queue[doc_idx][section_idx]->estimated_lines) {
req->next = section_queue[doc_idx][section_idx];
section_queue[doc_idx][section_idx] = req;
} else {
WriteRequest *cur = section_queue[doc_idx][section_idx];
while (cur->next && cur->next->estimated_lines <= line_count)
cur = cur->next;
req->next = cur->next;
cur->next = req;
}
pthread_cond_signal(§ion_queue_cond[doc_idx][section_idx]);
pthread_mutex_unlock(§ion_queue_mutex[doc_idx][section_idx]);
pthread_mutex_lock(§ion_mutex[doc_idx][section_idx]);
while (section_queue[doc_idx][section_idx]->client_sock != client_sock)
pthread_cond_wait(§ion_queue_cond[doc_idx][section_idx], §ion_mutex[doc_idx][section_idx]);
pthread_mutex_lock(&docs_mutex);
doc->section_line_count[section_idx] = 0;
for (int i = 0; i < line_count && i < MAX_LINES; ++i)
strncpy(doc->section_contents[section_idx][i], temp_lines[i], MAX_LINE - 1);
doc->section_line_count[section_idx] = line_count;
pthread_mutex_unlock(&docs_mutex);
section_queue[doc_idx][section_idx] = section_queue[doc_idx][section_idx]->next;
pthread_cond_broadcast(§ion_queue_cond[doc_idx][section_idx]);
pthread_mutex_unlock(§ion_mutex[doc_idx][section_idx]);
send_all(client_sock, "[Write_Completed]\n");
}
else if (strcmp(args[0], "read") == 0) {
pthread_mutex_lock(&docs_mutex);
if (argc == 1) {
for (int i = 0; i < doc_count; ++i) {
char line[BUF_SIZE];
snprintf(line, sizeof(line), "%s\n", docs[i].title);
send_all(client_sock, line);
for (int j = 0; j < docs[i].section_count; ++j) {
snprintf(line, sizeof(line), " %d. %s\n", j + 1, docs[i].section_titles[j]);
send_all(client_sock, line);
}
}
} else if (argc >= 3) {
Document* doc = find_doc(args[1]);
if (!doc) {
pthread_mutex_unlock(&docs_mutex);
send_all(client_sock, "[Error] Document not found.\n");
continue;
}
int found = 0;
for (int i = 0; i < doc->section_count; ++i)
if (strcmp(doc->section_titles[i], args[2]) == 0) {
found = 1;
char header[BUF_SIZE];
snprintf(header, sizeof(header), "%s\n %d. %s\n", doc->title, i + 1, doc->section_titles[i]);
send_all(client_sock, header);
for (int j = 0; j < doc->section_line_count[i]; ++j) {
char line[BUF_SIZE];
snprintf(line, sizeof(line), " %s\n", doc->section_contents[i][j]);
send_all(client_sock, line);
}
break;
}
if (!found)
send_all(client_sock, "[Error] Section not found.\n");
}
send_all(client_sock, "__END__\n");
pthread_mutex_unlock(&docs_mutex);
}
else if (strcmp(args[0], "bye") == 0) {
send_all(client_sock, "[Disconnected]\n");
break;
} else {
send_all(client_sock, "[Error] Unknown command.\n");
}
for (int i = 0; i < argc; ++i) free(args[i]);
}
close(client_sock);
return NULL;
}
0 XDK (+0)
유익한 글을 읽었다면 작성자에게 XDK를 선물하세요.
-
국어 2컷 0 0
공통에서만 -10점 90점인데… 이거 3등급인가요??ㅜㅜ 지구과학도 1점차이...
-
우웅 6 0
오부이 배고푼대 햄부거 두 개 먹으면 안 대 오 두 개 먹을래용
-
6섶 생1 0 0
정석준 인실모 풀다가 6섶 푸니까 인간실격모의고사가 아니라 출제자실격모의고사네 ㅅㅋ
-
학원 휴무됨 청년 1 0
이게아인데...
-
6섶 화작 95 0 1
21 45틀 문학 첫지문부터 선지 너무 어려워서 놀램:; 화작 45 <-화작에 대한...
-
전국의 한지러들에게.. 0 1
오늘 이위다까지 다 들었는데 도움 ㅈㄴ됨. 한지 과목 특성인지 처음에는 이런걸...
-
재수생 6섶 1 0
언매 86(문학만 틀;;;) 확통 88 영어 2(89;;;;) 경제 45 시문 42
-
시대 6월례 결과! 10 0
언매 : 100 미적: 96 (28틀) 영어: 81 (죽는줄 알았다…) 물1: 43...
-
물1, 생1은 상황 어떰? 2 0
고였나요
-
사탐 고수분들 0 0
제가 생윤 사문하는데 생윤은 개념 끝나고 이제 문제 풀려고 하고 사문은 2개월에...
-
작수 확통 백분위 70 에서 80올리는게 쉬울까요? 작수 영어 72점에서 82점으로...
-
수능날 공식 가채점표에 안적고 4 0
걍 수험표 뒷면에다 갈겨써도 될려나? 번호칸 나눠져 있는거 넘 불편할거같아서,, 감바감일거같긴한데
-
시간 왤케 안 가지 0 0
...
-
립 글로스 메이킴 fㅓ쓰 커스 암어 메킷 월크!!!!
-
월례 결산 2 2
언미물2지2 80 92 41 44 5섶이랑 점수 분포가 되게 비슷하네 난이도는...
-
이건 좀 심각하네요.... 3 2
이제 공대교수님이 지구과학이라도 했으면 다행이라고 생각할 정도네요
-
6섶 라인예측 해주실분 2 0
언매 84 미적 88 영어 1 한지 50(중) 세지 47(불)
-
미확기 다 있으니 논술러들은 풀어볼만도
-
국경의 긴 터널을 빠져나오자 설국이었다. 国境の長いトンネルを抜けると雪国であった。 -...
-
문학 15분컷을 보여주마 0 0
강E분 전체 외우기 ON
-
작수랑 백분위 비교해보면 6 0
국어와 물2 등가교환 한 느낌임 95 99 2 84 95(1컷) -> 89 99 2 94 98
-
수학 기출 1회독 기준? 1 0
기출문제집 아무거나 풀면 1회독안가요?아니면 6개년 정도 6, 9, 수능 풀모고 풀이하는 건가요?
-
바로 내신반영 질문해버리기 0 1
내신반영 하는 대학 설명회 들을때마다 분탕치기
-
요 따위의 문제를 철저히 대비하려면 양치기 밖에 없나요..? 진짜 현장에서 이런거...
-
근데 6모 등급컷 나온거에요? 1 0
왜 난 안보이지
-
6섶 4 0
미적 92 백분위 100뜨나요?
-
돈 없어서 4 2
3끼 라면 먹어야함
-
통합이후 수능에서는 한번도 연계가 안돼서 귀납적으로 보면 올해도 안되는게 정배긴...
-
국어는진짜 0 1
어케해야하는거냐 국어이샛키때문에 열받음;;;;;;;
-
저녁은 뷔페 1 1
치킨 많이 먹어야짛ㅎㅎ
-
선유도공원 가본사람 3 1
집 근처라서 버람 쐬러 갈건데 괜찮은가?
-
시방 오늘 저녁은 빠아스여 3 1
이 시벨롬(불어)들아
-
4페는 현장에서 도저히 못풀어서 다찍음 걍 계산량이 너무많았음... 18번 ㄷ선지...
-
아주 쉽게 적백 받는법 0 1
표점 100점
-
6모 4뜰듯 뭐지
-
지하철에서 서강대생 만남 3 1
같은아파트 친구였는데 나 재수한다하니까 안타깝게보더라 엉엉
-
모교로 성적표 찾으러 못가는데 0 0
군바리라 성적표 받으러 못가는데 전화로 성적표 사진이나 파일 달라하면 주나
-
기하92점 130이라던데 6 0
그럼 만표 136에 2점차인듯 개꿀인데? 100 136 100 96 133 99 92 130 97
-
데이트중 ㅎㅎ 3 2
컴퓨터 업데이트 씨발아
-
그래서 과탐 표본 얼마나 고인거임 11 2
시즌6974번째 호들갑임 아니면 ㄹㅇ개ㅈ된거임 ㅇ?ㅇ
-
6모만 2등급임 ㅅㅂ^^
-
립 글로스 메이킴 fㅓ쓰 커스 암어 메킷 월크!!!!
-
사실 물투 버린이유 1 2
이번학기 개쳐노니까 CC빔맞을각이라버림 못해서도 맞음
-
탐구 관련 조언 구합니다 1 0
2024년도에 시험 마지막으로 보고 7월부터 시작해서 수능보려는 반수생입니다. 제가...
-
물리학2 2 1
1컷 48인건 놀랍지않다 난 48-85-61 출신이니까...
-
재수생 시간배분 1 0
6모 64453인데 하루에 12시간 한다치면 시간 배분 어케 하는게 가장 이상적임?
-
작수는 해석이 어려운데 답은 금방금방 보였음 올6은 해석은 할만한데 답이 안보였음...
-
기하 만백은 100이겟지 1 1
-
생윤 개념 인강 추천 좀 0 0
인강 개념 빠르게 떼고 코드원 풀커리 탈 건데 ㅊㅊ 좀
-
단 59명


반가워요