3 7 SOCK SAP C 包裝類程式設計

2021-04-07 07:08:02 字數 1858 閱讀 1427

sock sap實現的客戶端

#include

#include

#include

static const int port_num = 10000;

static const int timeout = 5;

// sock_sap client.

template

void send_data(typename connector::peer_addr peer_addr)

*/// 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 ();

}sock sap實現的伺服器端

#include

#include

#include

static const int port_num = 10000;

// sock_sap server.

template

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

recv_data(addr);

return 0;