[C++] Socket server
C++ μλκ³ Cλ‘ μμΌν΅μ μμ±νκΈ°!
λ¬Έμ μ μ
μλ² μν : read
μνλ λ©μΈμ§λ₯Ό read ν΄λ³΄μ
μ½λ
void error_handling(const char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
int main()
{
int serv_sock = -1;
// μμΌ FD μμ±
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
if (serv_sock == -1)
{
error_handling("socket() error");
}
// μ£Όμ μ 보 μ΄κΈ°ν
struct sockaddr_in serv_addr, clnt_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(ip);
serv_addr.sin_port = htons(port);
// μμΌμ μμμ μμ±ν μ£Όμ μ 보λ₯Ό ν λΉ
if (bind(serv_sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) == -1)
{
error_handling("bind() error");
}
// ν΄λΌμ΄μΈνΈκ° μ°κ²° μμ²μ΄ κ°λ₯νλλ‘ 5ν¬κΈ°μ λκΈ°μ€ μμ±
if (listen(serv_sock, 2) == -1)
{
error_handling("listen() error");
}
// accept() ν¨μ νΈμΆμ ν΄μ μ€μ λ°μ΄ν°λ₯Ό λ³΄λΌ μ μλ μμΌμ μμ±
socklen_t clnt_addr_size = sizeof(clnt_addr);
int clnt_sock = accept(serv_sock, (struct sockaddr*)& clnt_addr, &clnt_addr_size);
if (clnt_sock == -1)
{
error_handling("accept() error");
}
// μ±κ³΅μ μΌλ‘ μλ²μκ²μ λ©μμ§λ₯Ό λ°μμ€λ©΄
// 0μ λ°ννκ³ μ€ν¨νλ©΄ -1μ λ°ννλ€.
char message[30];
int str_len;
while(1)
{
str_len = read(clnt_sock, message, sizeof(message)-1);
printf("Send message to server: %s \n", message);
}
}
Leave a comment