关闭

3.7 SOCK SAP C++包装类编程

标签: sapc++streamserverclasssocket
1569人阅读 评论(0) 收藏 举报
分类:

SOCK SAP实现的客户端

#include <ace/INET_Addr.h>
#include <ace/Time_Value.h>
#include <ace/SOCK_Connector.h>


static const int PORT_NUM = 10000;
static const int TIMEOUT = 5;

// SOCK_SAP Client.

template <class CONNECTOR>
void send_data(typename CONNECTOR::PEER_ADDR peer_addr)
{
 // Data transfer object.
 CONNECTOR::PEER_STREAM peer_stream;
 // Establish connection without blocking.
 CONNECTOR connector(peer_stream, peer_addr);


 /*if (peer_stream.get_handle() == NULL)
 {*/
  // If non-blocking connection is in progress,

  // wait up to TIMEOUT seconds to complete.

  /*ACE_Time_Value timeout(TIMEOUT);
  if (errno != EWOULDBLOCK ||connector.complete(peer_stream, &peer_addr, &timeout) == -1)
   perror ("connector");
  exit (1);*/
 /*}*/
 // Send data to server (send_n() handles
 // "short writes" correctly).
 char buf[BUFSIZ];
 for (int r_bytes;(r_bytes = read (0, buf, sizeof buf))>0;)
  peer_stream.send_n (buf, r_bytes);
 // Explicitly close the connection.
 peer_stream.close ();
}

int main (int argc, char *argv[])
{
 //char *host = argc > 1 ? argv[1]:"ics.uci.edu";
 //u_short port_num = htons (argc > 2?atoi (argv[2]):PORT_NUM);
 // Address of the server
 ACE_INET_Addr addr("10000","127.0.0.1");
 // Use SOCK SAP wrappers on client’s side.
 send_data<ACE_SOCK_Connector> (addr);
 return 0;
}

 

SOCK SAP实现的服务器端

#include <ace/INET_Addr.h>
#include <ace/Time_Value.h>
#include <ace/SOCK_Acceptor.h>


static const int PORT_NUM = 10000;

// SOCK_SAP Server.


template <class ACCEPTOR>
void recv_data (typename ACCEPTOR::PEER_ADDR addr)

{

 // Factory for passive connection establishment.

 ACCEPTOR acceptor(addr);

 // Data transfer object.

 ACCEPTOR::PEER_STREAM peer_stream;


 // Remote peer address.

 ACCEPTOR::PEER_ADDR peer_addr;

 // Performs iterative server activities.

 for (;;)

 {

  // Create a new STREAM endpoint

  // (automatically restarted if errno == EINTR).

  acceptor.accept (peer_stream, &peer_addr);

  printf ("client %s/n", peer_addr.get_host_name ());

  // Read data from client (terminate on error).

  char buf[BUFSIZ];

  for (int r_bytes = 0;;)

  {

   r_bytes = peer_stream.recv (buf, sizeof buf);

   if (r_bytes > 0)

    write (1, buf, r_bytes);

   else

    break;

  }

  // Close peer_stream endpoint

  // (acceptor endpoint stays open).

  peer_stream.close ();

 }

 /* NOTREACHED */

}

int main (int argc, char *argv[])

{

 u_short port_num = argc == 1 ? PORT_NUM : atoi (argv[1]);

 // Port for the server.

 ACE_INET_Addr addr (port_num);

 // Use Socket wrappers on server’s side.

 recv_data<ACE_SOCK_Acceptor> (addr);

 return 0;

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:29531次
    • 积分:529
    • 等级:
    • 排名:千里之外
    • 原创:23篇
    • 转载:1篇
    • 译文:0篇
    • 评论:1条
    文章存档
    最新评论