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);
  }
}

Reference

Leave a comment