ACE的TCP通信相当简单。服务器端用一个接受器Acceptor,这是个通信数据流Stream的工场模式。对于TCP,则分别为 ACE_SOCK_Acceptor和ACE_SOCK_Stream。对应的客户端则用一个连接器Connecter,这个也是数据流Stream的工 场模式。对于TCP,为ACE_SOCK_Connecter。TCP/IP通信用的地址则用ACE_INET_Addr类型。具体参考如下:
服务端:
#include <string>
#include <iostream>
#include <ace/SOCK_Stream.h>
#include <ace/SOCK_Acceptor.h>
int main(int argc, char* argv[])
{
char buf[1024];
ACE_SOCK_Stream stream;
ACE_INET_Addr addr (9999);
ACE_INET_Addr remote_addr;
ACE_SOCK_Acceptor acceptor(addr);
if (-1 == acceptor.accept(stream,&remote_addr))
return -1;
remote_addr.addr_to_string(buf,1024);
std::cout << "有客户端连接:" << buf << std::endl;
std::string str("TCP 服务端测试发送数据!");
stream.send(str.c_str(),str.length());
int size = stream.recv(buf,1024);
buf[size] = 0;
std::cout << "接收到数据:" << buf << std::endl;
system("pause");
return 0;
}
客户端:
#include <ace/SOCK_Stream.h>
#include <ace/SOCK_Connector.h>
int main(int argc, char* argv[])
{
char buf[1024];
ACE_INET_Addr server_addr(9999,"localhost");
ACE_SOCK_Stream stream;
ACE_SOCK_Connector connector;
if (-1 == connector.connect(stream,server_addr))
return -1;
server_addr.addr_to_string(buf,1024);
std::cout << "连接上服务器:" << buf << std::endl;
int size = stream.recv(buf,1024);
buf[size] = 0;
std::cout << "接收到数据:" << buf << std::endl;
std::string str = "客户端测试发送数据!";
stream.send(str.c_str(),str.length());
system("pause");
return 0;
}
下面是对服务端和客户端简单封装的类
//server
#define BUFFER_SIZE 1024
class server{
private:
char _data[BUFFER_SIZE];
ACE_INET_Addr _server_addr,_client_addr;
ACE_SOCK_Acceptor _acceptor;
ACE_SOCK_Stream _stream;
public:
server(int port) :_server_addr(port),
_acceptor(_server_addr){
_data[0]=0;
}
int accept(){
if(_acceptor.accept(_stream,&_client_addr/*,&__t*/)==-1){
ACE_ERROR ((LM_ERROR, "%p/n", "accept"));
return 0;
}
return 1;
}
int send(char* s) {
return _stream.send(s,strlen(s));
}
char* recv(){
int size=_stream.recv(_data,BUFFER_SIZE);
_data[size]=0;
return _data;
}
operator char* (){
return _data;
}
};
在server的构造函数中,先用一个端口号port初始化地址server_addr,然后用地址初始化接受器_acceptor。然后接受器可以用来 侦听(accept)客户端的连接,一旦有客户端连接,则设置TCP流_stream并保存客户端地址client_addr。连接成功后,则剩下的通信 工作转交给TCP流。类中的send和recv都是使用_stream的send和recv。 客户端有类似的代码:
//client
#define BUFFER_SIZE 1024
class client{
private:
char _data[BUFFER_SIZE];
ACE_INET_Addr _server_addr;
ACE_SOCK_Connector _connector;
ACE_SOCK_Stream _stream;
public:
client(char* hostname,int port)
:_server_addr(port,hostname){
_data[0]=0;
}
int connect(){
if(_connector.connect(_stream,_server_addr)==-1)
return 0;
return 1;
}
int send(char* s){
return _stream.send(s,strlen(s));
}
char* recv(){
int size=_stream.recv(_data,BUFFER_SIZE);
_data[size]=0;
return _data;
}
operator char*(){
return _data;
}
};
ACE的TCP通信
最新推荐文章于 2023-02-11 15:28:27 发布