|
发表于 2009-10-22 15:59:02
|
显示全部楼层
#include "ace/Reactor.h"
#include "ace/Svc_Handler.h"
#include "ace/Acceptor.h"
#include "ace/Synch.h"
#include "ace/SOCK_Acceptor.h"
#include "ace/SOCK_Connector.h"
#include "ace/OS.h"
#include "ace/Log_Msg.h"
#include <iostream>
#define PORT_NUM 19999
#define DATA_SIZE 13
class My_Svc_Handler;
typedef ACE_Acceptor <My_Svc_Handler,ACE_SOCK_Acceptor>MyAcceptor;
class My_Svc_Handler:public ACE_Svc_Handler <ACE_SOCK_STREAM,ACE_NULL_SYNCH>
{
public:
My_Svc_Handler()
{
data= new char[DATA_SIZE];
}
int open(void*)
{
std::cout <<"Connection established" <<std::endl;
return ACE_Svc_Handler <ACE_SOCK_STREAM,ACE_NULL_SYNCH>::open();
}
int handle_input(ACE_HANDLE)
{
int byteCount = 0;
if ( (byteCount = this->peer().recv_n(data,DATA_SIZE)) == -1)
{
ACE_OS::printf(" << Error!\n");
}
else if (byteCount == 0) {
ACE_OS::printf(" client disconnected!\n");
return -1;
}
else {
data[byteCount] = 0;
ACE_OS::printf(" << %s\n",data);
}
return 0;
}
int handle_close(ACE_HANDLE, ACE_Reactor_Mask) {
ACE_OS::printf("handle_close() called!\n");
delete[] data;
return 0;
}
private:
char* data;
};
int main(int argc, char* argv[])
{
ACE_INET_Addr addr(PORT_NUM);
MyAcceptor acceptor(addr,ACE_Reactor::instance());
ACE_Reactor::instance()->run_event_loop();
return 0;
}
class Client
{
public:
Client( char *addr, int port )
:remoteAddr_( port, addr )
{
}
int ConnectToServer()
{
if ( connector_.connect( clientStream_, remoteAddr_ ) == -1 )
{
ACE_ERROR_RETURN ((LM_ERROR,"(%P|%t) %p\n","connection failed"),-1);
}
else
{
ACE_DEBUG ((LM_DEBUG,"(%P|%t) connected to %s\n",remoteAddr_.get_host_name()));
}
return 0;
}
int SendToServer()
{
char *buf = "Hello world!";
if( clientStream_.send_n( buf, ACE_OS::strlen(buf)+1, 0 ) != -1 )
{
ACE_DEBUG( (LM_DEBUG,"Send %s to server succeed!\n", buf) );
}
else
{
ACE_DEBUG( (LM_DEBUG,"Send %s to server failed!\n", buf) );
}
//ACE_OS::sleep(1);
clientStream_.close();
return 0;
}
private:
ACE_INET_Addr remoteAddr_;
ACE_SOCK_Connector connector_;
ACE_SOCK_Stream clientStream_;
};
int main_client( int argc, char *argv[] )
{
char *remoteAddr = "127.0.0.1";
int port = 19999;
Client client( remoteAddr, port );
client.ConnectToServer();
client.SendToServer();
return 0;
};
[ 本帖最后由 wishel 于 2009-10-23 16:28 编辑 ] |
|