代码

普通的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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值