op_client
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 1024
#define RLT_SIZE 4
#define OPSZ 4
void error_handling(char *message);
int main(int argc, char *argv[]) {
int sock;
char opmsg[BUF_SIZE];
int result, opnd_cnt, i;
struct sockaddr_in serv_adr;
if (argc != 3) {
printf("Usage: %s <IP> <port>\n", argv[0]);
exit(1);
}
// Create socket
sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock == -1)
error_handling("socket() error");
// Initialize server address struct
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = inet_addr(argv[1]);
serv_adr.sin_port = htons(atoi(argv[2]));
// Connect to server
if (connect(sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1)
error_handling("connect() error!");
else
puts("Connected...........");
// Get operand count from user
fputs("Operand count: ", stdout);
scanf("%d", &opnd_cnt);
opmsg[0] = (char)opnd_cnt;
// Get operands from user
for (i = 0; i < opnd_cnt; i++) {
printf("Operand %d: ", i + 1);
scanf("%d", (int*)&opmsg[i * OPSZ + 1]);
}
// Clear buffer
fgetc(stdin);
// Get operator from user
fputs("Operator: ", stdout);
scanf("%c", &opmsg[opnd_cnt * OPSZ + 1]);
// Send message to the server
write(sock, opmsg, opnd_cnt * OPSZ + 2);
// Receive result from the server
read(sock, &result, RLT_SIZE);
// Print the result
printf("Operation result: %d \n", result);
// Close socket
close(sock);
return 0;
}
void error_handling(char *message) {
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
op_server
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 1024
#define OPSZ 4
void error_handling(char *message);
int calculate(int opnum, int opnds[], char oprator);
int main(int argc, char *argv[]) {
int serv_sock, clnt_sock;
char opinfo[BUF_SIZE];
int result, opnd_cnt, i;
int recv_cnt, recv_len;
struct sockaddr_in serv_adr, clnt_adr;
socklen_t clnt_adr_sz;
if (argc != 2) {
printf("Usage: %s <port>\n", argv[0]);
exit(1);
}
// Create socket
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
if (serv_sock == -1)
error_handling("socket() error");
// Initialize server address structure
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_adr.sin_port = htons(atoi(argv[1]));
// Bind the socket
if (bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1)
error_handling("bind() error!");
// Listen for connections
if (listen(serv_sock, 5) == -1)
error_handling("listen() error!");
clnt_adr_sz = sizeof(clnt_adr);
for (i = 0; i < 5; i++) {
opnd_cnt = 0;
clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_sz);
read(clnt_sock, &opnd_cnt, 1);
recv_len = 0;
while ((opnd_cnt * OPSZ + 1) > recv_len) {
recv_cnt = read(clnt_sock, &opinfo[recv_len], BUF_SIZE - 1);
recv_len += recv_cnt;
}
// Calculate result based on operands and operator
result = calculate(opnd_cnt, (int*)opinfo, opinfo[recv_len - 1]);
write(clnt_sock, (char*)&result, sizeof(result));
close(clnt_sock);
}
close(serv_sock);
return 0;
}
// Function to perform the operation based on the operator received
int calculate(int opnum, int opnds[], char op) {
int result = opnds[0], i;
switch (op) {
case '+':
for (i = 1; i < opnum; i++) result += opnds[i];
break;
case '-':
for (i = 1; i < opnum; i++) result -= opnds[i];
break;
case '*':
for (i = 1; i < opnum; i++) result *= opnds[i];
break;
}
return result;
}
// Function to handle errors by displaying the message and exiting
void error_handling(char *message) {
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
op_server부터 분석하겠습니다.
Serv_sock 소켓을 생성하고, 서버의 주소 정보를 serv_adr에 설정합니다. 이 주소 구조체는 서버의 IP주소와 포트 번호를 포함합니다.
소켓을 서버 주소에 바인딩하여 서버가 클라이언트 연결을 기다릴 수 있게 한 후, listen함수로 클라이언트 연결 요청을 대기하는 대기열 크기를 5로 설정합니다.
Accept 함수를 호출하여 클라이언트의 연결 요청을 수락하고, 새로운 소켓 clnt_sock을 생성합니다. 서버는 read함수를 통해 클라이언트로부터 피연산자의 개수(opnd_cnt)를 1바이트 읽어 옵니다.
Recv_len을 초기화하고, 필요한 바이트 수(opnd_cnt * OPSZ +1 ) 가 모두 수신될 떄까지 데이터를 계속 읽어옵니다. Opnd_cnt * OPSZ 는 각 연산자는 4바이트이므로 전체 피연산 자의 크기는 opnd * OPSZ가 됩니다.
루프는 데이터를 여러 번에 걸쳐 opinfo 버퍼에 읽어 들이며, 각 읽기에서 수신된 바이트 수를 recv_len에 누적합니다.
Calculate 함수에 피연산자 배열과 연산자를 전달하여 계산을 수행합니다. Calculate는 받은 연산자를 이용해 덧셈,뺼셈,곱셈을 수행합니다.
Opinfo[recv_len-1]은 연산자를 나타내며 opinfo 버퍼의 마지막 바이트에 저장된 연산자를 가져옵니다. 그 후, wirte함수를 사용하여 계산 결과를 클라이언트에 전송합니다
즉, 클라이언트로 데이터를 받아, 핵심처리는 서버에서 진행하는 재미있는 구조였습니다.
소켓을 생성하고, 서버의 ip주소와 포트를 설정한 후 connect를 시도합니다. 연결이 성공하면 Connect…….메시지를 출력합니다.
사용자에게 피연산자 개수를 입력받아 opnd_cnt 변수에 저장하고, 이를 opmsg[0]에 저장하여 서버로 보낼 데이터의 첫 바이트에 피연산자 개수를 포함시킵니다. 이 정보로 서버가 얼마나 많은 피연산자를 처리하는지 알 수 있도록 합니다.
For 루프를 통해 피연산자를 opnd_cnt만큼 입력받습니다. 각 피연산자는 4바이트 정수로 저장되며, opmsg 배열의 두 번째 위치부터 저장됩니다. Opmsg 배열의 첫 번째 바이트는 피연산자 개수(opnd_cnt)이고, 그 다음부터 각 피연산자 값이 차례로 저장됩니다.
Fgetc를 통해 입력 버퍼를 비워서 피연산자 뒤에 남아있을 수 있는 개행 문자를 제거합니다. 이후 scanf를 통해 연산자를 입력 받고 opmsg 배열이 피연산자 이후 위치에 저장합니다. 예를 들어 피연산자가 3개라면 연산자는 opmsg[3 * 4 +1],즉 opmsg[13]에 저장됩니다.
서버로 피연산자 개수+ 피연산자+연산자를 포함한 opmsg 배열을 전송 후, 서버에서 전달해주는 연산결과를 정수로 읽어서 result 변수에 저장합니다.
서버 실행 후, 클라이언트에서 operand count 및 피연산자 배열, 연산자를 건네주어 서버에서 실행 한 후, 클라이언트에서 받은 결과 값입니다.
'프로그래밍 > 2024 네트워크 프로그래밍' 카테고리의 다른 글
10. 구조체 헤더를 이용한 소켓통신 - 서버 코드 살펴보기 (0) | 2025.01.14 |
---|---|
9. 구조체 헤더를 이용한 소켓통신 - 클라이언트와 헤더파일 살펴보기 (0) | 2025.01.14 |
7. read를 사용한 에코 클라이언트 최적화 (0) | 2025.01.08 |
6. Address conversion (0) | 2025.01.06 |
5. inet_addr 살펴보기 (0) | 2025.01.06 |