Client:
#include "ace/Log_Msg.h" #include "ace/OS.h" #include "ace/Service_Config.h" #include "ace/Event_Handler.h" #include "ace/Reactor.h" #include "ace/Svc_Handler.h" #include "ace/SOCK_Stream.h" #include "ace/Connector.h" #include "ace/SOCK_Connector.h" class CClientHandler : public ACE_Svc_Handler <ACE_SOCK_STREAM, ACE_NULL_SYNCH> { private: char* data; static const int stDataSize = 64; public: CClientHandler() { data = new char[stDataSize]; } int open(void*) { ACE_DEBUG((LM_DEBUG,ACE_TEXT("client connection established.\n"))); ACE_Reactor::instance()->register_handler(this, ACE_Event_Handler::READ_MASK); char *message = "Client connected successfully in client.\n"; peer().send(message, strlen(message) + 1); return 0; } int handle_input(ACE_HANDLE) { peer().recv(data, stDataSize); ACE_DEBUG((LM_DEBUG, "data:%s\n", data)); return 0; } }; int main(int argc, char* argv[]) { const int cPort = 12344; ACE_INET_Addr addr(cPort, "localhost"); ACE_Connector<CClientHandler, ACE_SOCK_CONNECTOR> connector; CClientHandler *handler = new CClientHandler(); if(connector.connect(handler, addr) == -1) { ACE_ERROR((LM_ERROR, "%P|%t, %s", "Connection failed.\n")); } ACE_Reactor::run_event_loop(); return 0; }
Server:
#include "ace/Log_Msg.h" #include "ace/OS.h" #include "ace/Service_Config.h" #include "ace/Event_Handler.h" #include "ace/Reactor.h" #include "ace/Svc_Handler.h" #include "ace/SOCK_Stream.h" #include "ace/Acceptor.h" #include "ace/SOCK_Acceptor.h" class CServerHandler : public ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_NULL_SYNCH> { private: char* data; static const int stDataSize = 64; public: CServerHandler() { data = new char[stDataSize]; } int open(void *) { ACE_DEBUG((LM_INFO, "%P|%t, %s", "Server Connection established.\n")); ACE_Reactor::instance()->register_handler(this, ACE_Event_Handler::READ_MASK); char *message = "Client connected successfully in server.\n"; peer().send(message, strlen(message) + 1); return 0; } int handle_input(ACE_HANDLE) { ssize_t recv_size = peer().recv(data, stDataSize); if (recv_size <= 0) { ACE_DEBUG((LM_WARNING, " No data received.\n")); } else { ACE_DEBUG((LM_DEBUG, "data:%s\n", data)); char *message = "Request is processed successfully!\n"; peer().send(message, strlen(message) + 1); } return 0; } }; int main(int argc, char* argv[]) { ACE_DEBUG((LM_DEBUG,"Test server running...\n")); const int cPort = 12344; ACE_INET_Addr addr(cPort); ACE_Acceptor<CServerHandler, ACE_SOCK_ACCEPTOR> acceptor; if (acceptor.open(addr) == -1) { ACE_DEBUG((LM_WARNING, "Accept error.\n")); } ACE_Reactor::run_event_loop(); return 0; }
时间: 2024-10-30 07:39:18