/*
  PeerConnection のサンプル
  Satofumi KAMIMURA
  $Id: peerConnect.cpp 286 2008-10-20 09:40:22Z satofumi $
*/

#include "peerConnection.h"
#include <stdio.h>
#include <stdlib.h>


static void recvWithTimeout(PeerConnection& con,
			    long timeout = 0, int checkInterval = 100) {
  int noReply = 0;
  char buffer[BUFSIZ];
  do {
    int n = con.recv(buffer, BUFSIZ-1, checkInterval);
    if (n <= 0) {
      noReply += checkInterval;

    } else {
      noReply = 0;
      for (int i = 0; i < n; ++i) {
	putchar(buffer[i]);
      }
      putchar('\n');
    }
  } while (noReply < timeout);
}


int main(int argc, char *argv[]) {
  enum {
    ConnectionTimeout = 5000,
    RecvTimeout = 1000,
    RecvPollTime = 100,
  };
  try {
    if (argc < 3) {
      printf("Usage : \n%s <host> <port> [<message>]\n", argv[0]);
      exit(1);
    }

    // 接続処理
    PeerConnection con;
    if (con.connect(argv[1], atoi(argv[2]), ConnectionTimeout) < 0) {
      printf("connection timeout!\n");
      exit(1);
    }

    // 送信
    const char* message = (argc > 3) ? argv[3] : "hello";
    con.send(message, strlen(message));

    // 受信待ち
    recvWithTimeout(con, RecvTimeout, RecvPollTime);
  } catch (std::exception& e) {
    printf("exception: %s\n", e.what());
  }
  return 0;
}
