/*
  TCP/IP 通信の Linux 実装
  Satofumi KAMIMURA
  $Id: tcpip_sample.c 286 2008-10-20 09:40:22Z satofumi $
*/

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/poll.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>


int tcpip_recv(struct pollfd *nfds, char *data, int size, int timeout) {
  int fd = nfds->fd;
  int filled = 0;
  int n;

  while (filled < size) {
    if (poll(nfds, 1, timeout) == 0) {
      break;                    // timeout
    }
    n = read(fd, &data[filled], size - filled);
    if (n <= 0) {
      break;
    }
    filled += n;
  }
  return filled;
}



int main(int argc, char *argv[]) {
  int sockfd;
  struct sockaddr_in address;
  struct pollfd nfds;
  int len;
  int result;
  char ch;

  // サーバに接続
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = inet_addr("localhost");
  address.sin_port = htons(9314);
  len = sizeof(address);

  result = connect(sockfd, (struct sockaddr*)&address, len);
  if (result < 0) {
    perror("connect");
    exit(1);
  }

  // poll() 用の設定
  nfds.fd = sockfd;
  nfds.events = POLLIN | POLLPRI | POLLERR | POLLHUP | POLLNVAL;
  nfds.revents = 0;

  // 書き込み
  ch = 'a';
  result = write(sockfd, &ch, 1);
  printf("write: %d\n", result);

  // 読み出し
  ch = 'a' + 1;
  result = tcpip_recv(&nfds, &ch, 1, 1000);
  printf("recv: %d\n", result);
  if (result > 0) {
    printf("%c\n", ch);
  }

  return 0;
}
