1. Related to Class
Ace_inet_addr//ace Network Address
Ace_sock_acceptor//ace network Server
Ace_sock_connector//ace Network Client
Ace_sock_stream//ace Data Flow
2. Introduction
TCP Communication
TCP (Transmission Control Protocol): TCP provides reliable, connection-oriented transport services for high-reliability data transmission. The reliability of TCP protocol is to ensure that each TCP message can reach the client in the order of sending.
The TCP communication process is generally the following steps:
A) server-bound port, waiting for client connections.
b) The client connects to the server through the server's IP and server-bound ports.
c) The server and client set up a data path through the network to interact with the data through this data path.
3. Sample Code
1#include <iostream>2#include"Ace/sock_acceptor.h"3 using namespacestd;4 5 Const intServer_port = the ;6 intMainintargcChar*argv[])7 {8 Charbuffer[1024x768];9Ace_sock_stream peer;//Sock_io, and client-side data PathsTenAce_time_value Timeout ( -,0);//TCP Accept time-out One A //socket creation, binding, monitoring - ace_inet_addr Addr (server_port); - Ace_sock_acceptor acceptor; the if(Acceptor.open (addr)! =0)//Binding Port - { -cout<<"Bind Port fail!"<<Endl; - return-1; + } -cout<<"server ready."<<Endl; + A while(true) at { - if(Acceptor.accept (PEER)! =-1)//establishing and connecting to clients - { -std::cout<<"client connect."<<Std::endl; - while(true) - { in - if(Peer.recv (Buffer,1024x768, &timeout) <=0)//receive data (timeout or break on end) to { + Break; - } thecout<<"[Server rev]:>"<<buffer<<Endl; * if(strcmp (Buffer,"quit") ==0) $ {Panax Notoginseng Break; - } the Do + { Acout<<"[Server cin]:>"; theCin.getline (Buffer,1024x768); +} while(strlen (buffer) <=0); -Peer.send (buffer, strlen (buffer));//Send Data $ $ } - peer.close (); - } the } - Wuyi return 0; the}
Server.cpp
1#include <ace/SOCK_Connector.h>2 3#include <string>4#include <iostream>5 using namespacestd;6 7 Const intServer_port = the ;8 9 intMainintargcChar*argv[])Ten { One Charbuffer[1024x768]; A -Ace_inet_addr Addr ( the,"192.168.237.128"); -Ace_time_value Timeout ( -,0); the Ace_sock_stream peer; - ace_sock_connector Connector; - if(Connector.connect (peer,addr,&timeout)! =0) - { +cout<<"Connection Failed!"<<Endl; - return-1; + } Acout<<"conneced!"<<Endl; at - while(true) - { - Do - { -cout<<"[Client cin]:>"; inCin.getline (Buffer,1024x768); -} while(strlen (buffer) <=0); toPeer.send (buffer, strlen (buffer));//Send Data + - if(Peer.recv (Buffer,1024x768, &timeout) <=0)//receive data (timeout or break on end) the { * Break; $ }Panax Notoginsengcout<<"[Client rev]:>"<<buffer<<Endl; - if(strcmp (Buffer,"quit") ==0) the { + Break; A } the } + peer.close (); - $ return 0; $}
client.cpp
ACE_LINUX:TCP Communication