ACE中的TCP通讯

来源:互联网 发布:淘宝装修用什么版本? 编辑:程序博客网 时间:2024/06/06 14:20

ACE中的TCP通讯,不罗嗦,直接上代码。

服务器代码:

#include "ace/SOCK_Acceptor.h"#include "ace/SOCK_Stream.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 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; } 


客户端代码:

#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<<"recv:\t"<<buf<<endl;    }    peer.close();getchar();    return 0; } 


编译执行,结果如下。

服务器:

client connect.

local port      localhost       3000

 

客户端:

conneced !

send:   hello world

recv:    hello world

参考:

http://www.cnblogs.com/TianFang/archive/2006/12/07/585095.html

0 0
原创粉丝点击