Linux下簡單的ACE socket客戶端和伺服器端

大囚長發表於2019-01-28

安裝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

相關文章