컴공 일기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를 선물하세요.
-
#07년생#08년생#독학생 오르비의 주인이 될 기회 37 36
-
수바 97 0 0
분컷 89 ㅁㅌㅊ
-
근데 언젠가는 모두가 부남에게 치료받아야된다는거아니야 2 0
아이고두야
-
아무도 없군 3 0
이제부터 여기는
-
오르비 헬스터디 어떰 3 0
오르비 고닉들이 쌩노베 엔수생 한명을 가둬놓고 원하는대로 가르쳐보는거임
-
ㅅㅂ 23년도 1월부터 했었는데 ㅋㅋㅋㅋㅋ 중3땐가 그때부터 ㅋㅋㅋ
-
작년 8월 이후에 자퇴해서 이번 검정고시를 볼 수 없는데, 6모 볼 수 있는 학원이...
-
나는 내가 문과 학교에 가면 수학을 쌀먹할 수 있을 줄 알았어 8 1
아니더라 ㅅㅂ
-
은근호감이면 개추 8 3
-
벌써 수잘 떠오르는 오르비언만 10명이 넘는다
-
롤하기 1 0
-
지금 수학 ㅈㄴ 문제인데 10 0
수학이 손에 안잡힘
-
CC하고싶다 2 0
대학가서 미팅 나도 할래
-
우선 안란이 지금은 좀 쉽지 않아보이는데 버프 좀 받으면 굉장히재밋을듯...
-
라면먹고 라죽을 Yarr 10 0
참기름 냄새 죽인다
-
경한 자연 0 0
어디까지 돌까요? 쓰신 분들 알려주시면 너무너무 감사할거 같습니다! 경한 경희한 경희 한의
-
전필이랑 교필만 해도 최대학점의 거의 따블이 되는데 2 0
이게 맞음?
-
이재명 개 6 0
안주로 뭐 먹을까
-
내가찐따라미안해 1 0
2827₩:):):):₩:₩27/7₩/&! ㅠ.ㅠ 아웅
-
지금좀모순적인상태임 7 0
자신감도있고 내 능력을 꽤나 고평가하고있는 상태 자기혐오도 크지 않고 외모정병도없고...
-
갑자기 든 생각인데 0 2
설수리만 수리논술 열어주면 재밋겟다.. ㄹㅇ 천하제일 논술대회 될듯 올림피아드 될거같은디
-
이새끼는공부를안하나 7 0
똥글만싸지르네...
-
이새끼 나만 재밋냐 3 0
존나웃김걍
-
이렇게 클린할수가 평생 퐁퐁이라도 당하면 천운이 따른거고 여자 못만날것처럼 갤에서...
-
본인의외로코코이잘안침 1 0
1달4딸도안함 코코이치면 체력소모가 너무큼
-
왜 붙은거지 10 2
나 ㄹㅇ 이세계 주인공 머 그런건가
-
윤석열 지지를 어케하나료 9 2
그양반은 보수가 아니라 민주당 쁘락치라고 생각합니다
-
자취하면 2 0
부모님께자취방주소도안알려주고싶다 는생각을한다
-
나도제정신은아니다싶어 17 0
문제풀다가 좆같으면 막 눈물나서 울면서 풂 죽고싶다 입시 생활이 빨리 끝났으면...
-
죽으럭사갗라료살려주세요 2 0
술미친 아 아속안좋아 적당히먿엇어야ㅏ햇은데 ㄴㅊ
-
인증 20 0
ㅋ
-
저 정치적 성향은 2 1
일단 보수임 윤어게인 쪽 아님 한동훈파 아님 이준석쪽이엿는데 맘에 안들음 걍 이명박...
-
설레는 편지 5 0
-
오르비잘자 6 1
-
mbti뭐임 2 0
본인은sexy임
-
뉴런 수분감 순서 3 0
뉴런 대단원 끝날때마다 수분감 스텝2 풀고 뉴런 듣고 이런식으로 반복하나요 아님...
-
지친다 6 0
노래들으며 픽시브 핀터레스트에서 일러스트나 찾아야겠다
-
원서는운이다 5 0
네
-
찢한테 박은 욕이 11 0
도련님 거기 찢지 마세요였나 기억 잘 안남 24년도라
-
97명인데 은테가 유지됨 4 0
유령들이 떠받쳐주고 있구나
-
찢이랑 사진찍기 11 2
이때 면전에 욕박았슨
-
의대증원 1 0
30년까지 증원하고 다시 3000명 정도로 복귀되는건가요 아니면 증원된 인원대로...
-
N제를 가장 잘 푸는 아이돌은? 13 2
NJZ(N제easy) 엌ㅋㅋㅋ
-
널내일이라 0 0
부를래
-
잘자오르비 4 0
ㅎ.ㅎ
-
집밖을안나가면 7 0
피부가안탐
-
손 ㅇㅈ 2 0
-
GMG,HMH 이 뭔지 암?? 16 0
내그 틀딱이냐?
-
20 7모 가형 문제 맛있는듯 0 0
전체적으로 ㅈ같은 문제하나 없이 무난하게 맛있음
-
피부색이 10 0
왜이렇게 어두워진거같지 기분탓인가

반가워요