Linux下简单的ACE socket客户端和服务器端

安装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;
}

编译命令同服务端

参考:
https://blog.csdn.net/lishuo102/article/details/7480139

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值