普通的iterator server and client
server
#include <sys/socket.h>
#include <string.h>
#include <cerrno>
#include <cstdlib>
#include <stdio.h>
#include <arpa/inet.h>
#include <string>
#include <iostream>
using namespace std;
int main( int argc, char* argv[] )
{
int listenfd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( listenfd < 0 )
{
cout << "socket error" << endl;
exit( 1 );
}
struct sockaddr_in addr;
bzero( &addr, sizeof( addr ) );
addr.sin_family = AF_INET;
addr.sin_port = htons( 8888 );
addr.sin_addr.s_addr = htonl( INADDR_ANY );
int r = bind( listenfd, ( struct sockaddr *)( &addr ), sizeof( addr ) );
if ( r < 0 )
{
cout << "bind error" << endl;
exit( 2 );
}
r = listen( listenfd, 1024 );
if ( r < 0 )
{
cout << "listen error" << endl;
exit( 3 );
}
while ( 1 )
{
int connfd = accept( listenfd, 0, 0 );
if ( connfd < 0 )
{
cout << "accept error" << endl;
exit( 4 );
}
time_t tm = time( 0 );
string str = ctime( &tm );
int c = write( connfd, str.c_str(), str.length() );
if ( c < 0 )
{
cout << "write error" << endl;
exit( 5 );
}
close( connfd );
}
return 0;
}
client
#include <sys/socket.h>
#include <cstdio>
#include <cerrno>
#include <cstdlib>
#include <string.h>
#include <arpa/inet.h>
#include <string>
#include <iostream>
using namespace std;
int main( int argc, char* argv[] )
{
if ( argc != 2 )
{
return 1;
}
struct sockaddr_in addr;
bzero( &addr, sizeof( addr ) );
addr.sin_family = AF_INET;
addr.sin_port = htons( 8888 );
int r = inet_pton( AF_INET, argv[ 1 ], &addr.sin_addr );
if ( r <= 0 )
{
cout << "inet_pton error" << endl;
exit( 2 );
}
int connfd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( connfd < 0 )
{
cout << "socket error" << endl;
exit( 1 );
}
r = connect( connfd, ( struct sockaddr *)( &addr ), sizeof( addr ) );
if ( r < 0 )
{
cout << "accept error" << endl;
exit( 4 );
}
char buf[ 2048 ];
bzero( buf, sizeof( buf ) );
int c = 0;
while ( ( c = read( connfd, buf, 2048 ) ) > 0 )
{
string str = buf;
cout << str << endl;
bzero( buf, sizeof( buf ) );
}
return 0;
}