コード例 #1
0
ファイル: Main.cpp プロジェクト: enuuros/multitude
void runClient(const char * host, int port, const char * message)
{
  printf("Setting up a client socket to %s:%d\n", host, port);

  TCPSocket socket;
  int err = socket.open(host, port);

  if(err) {
    const int  msgSize = 128;
    char  msgBuf[msgSize] = "";
    printf("%s cannot open client socket to %s:%d -> %s\n", 
	   appname, host, port, strerror_s(msgBuf, msgSize, err));
    return;
  }

  socket.setNoDelay(true);

  char buf[1024];

  for(int i = 0; i < iterations; i++) {

    puts("Sending message");

    sprintf(buf, "%s %d", message, i + 1);
    
    int32_t len = strlen(buf) + 1;
    socket.write( & len, 4);
    socket.write(buf, len);

    if(withreplies) {
      len = 0;
      socket.read( & len, 4);
      bzero(buf, sizeof(buf));
      socket.read(buf, len);
      printf("Received reply \"%s\"\n", buf);
    }
  }

  puts("Closing");

  socket.close();
}
コード例 #2
0
ファイル: Main.cpp プロジェクト: enuuros/multitude
void runServer(const char * host, int port, bool withBlocking)
{
  printf("Setting up a server socket to %s:%d\n", host, port);

  char buf[1024];

  TCPServerSocket server;
  int i, err = server.open(host, port, 5);
// err = server.open(0, port, 5)
  if(err) {
    const int  msgSize = 128;
    char  msgBuf[msgSize] = "";
    printf("%s cannot open server socket to %s:%d -> %s\n", 
	   appname, host, port, strerror_s(msgBuf, msgSize, err));
    return;
  }
  
  for(i = 0; i < 10; i++) {
    puts("Waiting for a connection");

    while(withBlocking && !server.isPendingConnection(1000000)) {
      printf(".");
      fflush(0);
    }

    TCPSocket * socket = server.accept();

    if(!socket) {
      Radiant::error("Could not create accept a socket connection.");
      return;
    }

    socket->setNoDelay(true);

    printf("Got a new socket %p\n", socket);
    fflush(0);

    for(int j = 0; j < iterations; j++) {
      int32_t len = 0;
      buf[0] = '\0';
      int n = socket->read( & len, 4);
      
      if(n != 4) {
	Radiant::error("Could not read 4 header bytes from the socket, got %d", n);
	delete socket;
	return;
      }
      
      n = socket->read(buf, len);
      
      if(n != len) {
	Radiant::error("Could not read %d data bytes from the socket, got %d",
		       len, n);
      }
      
      printf("Received \"%s\"\n", buf);

      if(withreplies) {
	socket->write( & len, 4);
	socket->write( & buf, len);
      }
    }

    delete socket;
  }
  
  fflush(0);

  info("%s %d clients handled, returning", appname, i);
}