安装ACE开发库
apt install libace-dev -y
服务端
#include "ace/SOCK_Acceptor.h"
#include "ace/SOCK_Stream.h"
#include "ace/INET_Addr.h"
#include "ace/OS.h"
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
ACE_INET_Addr port_to_listen(3000); //绑定的端口
ACE_SOCK_Acceptor acceptor;
if (acceptor.open(port_to_listen, 1) == -1) //绑定端口
{
cout << endl << "bind port fail" << endl;
return -1;
}
while (true) {
ACE_SOCK_Stream peer; //和客户端的数据通路
ACE_Time_Value timeout(10, 0);
if (acceptor.accept(peer) != -1) //建立和客户端的连接
{
cout << endl << endl << "client connect. " << endl;
char buffer[1024];
ssize_t bytes_received;
ACE_INET_Addr raddr;
peer.get_local_addr(raddr);
cout << endl << "local port\t" << raddr.get_host_name() << "\t" << raddr.get_port_number() << endl;
while ((bytes_received =
peer.recv(buffer, sizeof(buffer))) != -1) //读取客户端发送的数据
{
peer.send(buffer, bytes_received); //对客户端发数据
}
peer.close();
}
}
return 0;
}
编译命令
g++ aceserver.cpp -o aceserver -lACE
客户端
#include <ace/SOCK_Stream.h>
#include <ace/SOCK_Connector.h>
#include <ace/INET_Addr.h>
#include <ace/Time_Value.h>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
ACE_INET_Addr addr(3000, "127.0.0.1");
ACE_SOCK_Connector connector;
ACE_Time_Value timeout(5, 0);
ACE_SOCK_Stream peer;
if (connector.connect(peer, addr, &timeout) != 0)
{
cout << "connection failed !" << endl;
return 1;
}
cout << "conneced !" << endl;
string s = "hello world";
peer.send(s.c_str(), s.length()); //发送数据
cout << endl << "send:\t" << s << endl;
ssize_t bc = 0; //接收的字节数
char buf[1024];
bc = peer.recv(buf, 1024, &timeout); //接收数据
if (bc >= 0)
{
buf[bc] = '\0';
cout << endl << "rev:\t" << buf << endl;
}
peer.close();
return 0;
}
编译命令同服务端