Daytime.1 - A synchronous TCP daytime client
This tutorial program shows how to use asio to implement a client application with TCP.
We start by including the necessary header files.
本示例程序顯示如何使用Asio來(lái)實(shí)現(xiàn)一個(gè)TCP客戶端程序。
讓我們從添加必需的頭文件開始。
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
The purpose of this application is to access a daytime service, so we need the user to specify the server.
這個(gè)應(yīng)用程序的目的是訪問(wèn)一個(gè)daytime服務(wù)器,因此我們需要用戶去指定服務(wù)器。(如time-nw.nist.gov,用IP亦可)
using boost::asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
All programs that use asio need to have at least one boost::asio::io_service object.
所有使用asio的程序都至少需要一個(gè)boost::asio::io_service對(duì)象。
boost::asio::io_service io_service;
We need to turn the server name that was specified as a parameter to the application, into a TCP endpoint. To do this we use an boost::asio::ip::tcp::resolver object.
我們需要把服務(wù)器的名稱轉(zhuǎn)化為TCP的節(jié)點(diǎn),而該名稱是通過(guò)應(yīng)用程序的參數(shù)指定的。我們使用boost::asio::ip::tcp::resolver 對(duì)象來(lái)完成。
tcp::resolver resolver(io_service);
A resolver takes a query object and turns it into a list of endpoints. We construct a query using the name of the server, specified in argv[1]
, and the name of the service, in this case "daytime"
.
一個(gè)resolver對(duì)象獲得一個(gè)query對(duì)象,并將其轉(zhuǎn)換為節(jié)點(diǎn)列表.我們通過(guò)argv[1]中的服務(wù)器名稱和服務(wù)名,在這里是daytime,構(gòu)造一個(gè)query。
tcp::resolver::query query(argv[1], "daytime");
The list of endpoints is returned using an iterator of type boost::asio::ip::tcp::resolver::iterator. A default constructed boost::asio::ip::tcp::resolver::iterator object is used as the end iterator.
節(jié)點(diǎn)列表用 boost::asio::ip::tcp::resolver::iterator 類型的迭代器返回。返回的iterator將采用boost::asio::ip::tcp::resolver::iterator的默認(rèn)構(gòu)造函數(shù)來(lái)構(gòu)造。
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
Now we create and connect the socket. The list of endpoints obtained above may contain both IPv4 and IPv6 endpoints, so we need to try each of them until we find one that works. This keeps the client program independent of a specific IP version.
現(xiàn)在我們建立一個(gè)socket并連接之,由于獲得的節(jié)點(diǎn)既有IPv4也有IPv6的。所以,我們需要依次嘗試訪問(wèn)它們直到找到一個(gè)可以正常工作的。這樣做可使得我們的程序獨(dú)立于特定的IP版本。
tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
socket.close();
socket.connect(*endpoint_iterator++, error);
}
if (error)
throw boost::system::system_error(error);
The connection is open. All we need to do now is read the response from the daytime service.
We use a boost::array
to hold the received data. The boost::asio::buffer() function automatically determines the size of the array to help prevent buffer overruns. Instead of a boost::array
, we could have used a char []
or std::vector
.
連接打開后,現(xiàn)在我們需要做的就是讀取daytime服務(wù)器的響應(yīng)。
我們使用boost::array 來(lái)存放接收到的數(shù)據(jù)。boost::asio::buffer()函數(shù)會(huì)自動(dòng)確定array的長(zhǎng)度來(lái)防止緩沖區(qū)溢出。我們也可以使用 char []
或 std::vector來(lái)代替boost::array。
for (;;)
{
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
When the server closes the connection, the boost::asio::ip::tcp::socket::read_some() function will exit with the boost::asio::error::eof error, which is how we know to exit the loop.
當(dāng)服務(wù)器關(guān)閉連接時(shí),boost::asio::ip::tcp::socket::read_some()函數(shù)會(huì)以boost::asio::error::eof錯(cuò)誤標(biāo)志返回, 通過(guò)該錯(cuò)誤標(biāo)志,我們知道應(yīng)該退出循環(huán)了。
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
std::cout.write(buf.data(), len);
}
Finally, handle any exceptions that may have been thrown.
最后,處理所有可能拋出的異常 。
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
See the full source listing
完整代碼:
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], "daytime");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
socket.close();
socket.connect(*endpoint_iterator++, error);
}
if (error)
throw boost::system::system_error(error);
for (;;)
{
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
std::cout.write(buf.data(), len);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
Daytime.2 - A synchronous TCP daytime server
一個(gè)同步的TCP daytime服務(wù)器
This tutorial program shows how to use asio to implement a server application with TCP.
本示例示范如何使用Asio來(lái)實(shí)現(xiàn)一個(gè)TCP服務(wù)器程序。
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;
We define the function make_daytime_string()
to create the string to be sent back to the client. This function will be reused in all of our daytime server applications.
我們先定義一個(gè)make_daytime_string()來(lái)產(chǎn)生需要發(fā)送給客戶端的字符串.這個(gè)函數(shù)會(huì)在我們所有的daytime服務(wù)器上被使用。
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
boost::asio::io_service io_service;
A boost::asio::ip::tcp::acceptor object needs to be created to listen for new connections. It is initialised to listen on TCP port 13, for IP version 4.
新建一個(gè)asio::ip::tcp::acceptor對(duì)象來(lái)監(jiān)聽(tīng)新的連接。該對(duì)象應(yīng)遵守IPv4協(xié)議,監(jiān)聽(tīng)TCP端口13。

This is an iterative server, which means that it will handle one connection at a time. Create a socket that will represent the connection to the client, and then wait for a connection.
這是一個(gè)iterative server,也就是說(shuō)同一時(shí)間只能處理一個(gè)連接。建立一個(gè)表示與客戶端的連接的socket, 然后等待客戶端的連接。
for (;;)
{
tcp::socket socket(io_service);
acceptor.accept(socket);
A client is accessing our service. Determine the current time and transfer this information to the client.
std::string message = make_daytime_string();
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer(message),
boost::asio::transfer_all(), ignored_error);
}
}
Finally, handle any exceptions.
最后,
處理異常。
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
See the full source listing
全部源碼:
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));
for (;;)
{
tcp::socket socket(io_service);
acceptor.accept(socket);
std::string message = make_daytime_string();
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer(message),
boost::asio::transfer_all(), ignored_error);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
The main() function
主函數(shù)
int main()
{
try
{
We need to create a server object to accept incoming client connections. The boost::asio::io_service object provides I/O services, such as sockets, that the server object will use.
我們需要?jiǎng)?chuàng)建一個(gè)服務(wù)器對(duì)象,用來(lái)接受客戶端的連接。boost::asio::io_service對(duì)象提供了像sockets這樣的I/O服務(wù),這些服務(wù)都是服務(wù)器對(duì)象將要使用的。
boost::asio::io_service io_service;
tcp_server server(io_service);
Run the boost::asio::io_service object so that it will perform asynchronous operations on your behalf.
運(yùn)行boost::asio::io_service 對(duì)象,它將執(zhí)行你想要的異步操作。
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
The tcp_server class
TCP服務(wù)器類
class tcp_server
{
public:
The constructor initialises an acceptor to listen on TCP port 13.
構(gòu)造函數(shù)初始化一個(gè)用于監(jiān)聽(tīng)TCP 端口13的接收器。
tcp_server(boost::asio::io_service& io_service)
: acceptor_(io_service, tcp::endpoint(tcp::v4(), 13))
{
start_accept();
}
private:
The function start_accept()
creates a socket and initiates an asynchronous accept operation to wait for a new connection.
函數(shù)start_accept()創(chuàng)建一個(gè)socket ,同時(shí)啟動(dòng)一個(gè)異步接收操作去等待一個(gè)新的連接。
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(acceptor_.io_service());
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
The function handle_accept()
is called when the asynchronous accept operation initiated by start_accept()
finishes. It services the client request, and then calls start_accept()
to initiate the next accept operation.
當(dāng)start_accept()啟動(dòng)的異步接收操作完成后,handle_accept()函數(shù)將被調(diào)用。它響應(yīng)客戶端的請(qǐng)求,然后調(diào)用start_accept()函數(shù)去啟動(dòng)另一個(gè)接收操作。
void handle_accept(tcp_connection::pointer new_connection,
const boost::system::error_code& error)
{
if (!error)
{
new_connection->start();
start_accept();
}
}
The tcp_connection class
TCP連接類
We will use shared_ptr
and enable_shared_from_this
because we want to keep the tcp_connection
object alive as long as there is an operation that refers to it.
我們希望只要還有一個(gè)操作涉及tcp_connection對(duì)象,該對(duì)象就是有效的。因此我們使用shared_ptr 和enable_shared_from_this。
class tcp_connection
: public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& io_service)
{
return pointer(new tcp_connection(io_service));
}
tcp::socket& socket()
{
return socket_;
}
In the function start()
, we call boost::asio::async_write() to serve the data to the client. Note that we are using boost::asio::async_write(), rather than boost::asio::ip::tcp::socket::async_write_some(), to ensure that the entire block of data is sent.
在start()函數(shù)中,我們調(diào)用boost::asio::async_write()為客戶端處理數(shù)據(jù)。注意:為了確保數(shù)據(jù)被整塊發(fā)送,我們使用的是boost::asio::async_write(),而不是boost::asio::ip::tcp::socket::async_write_some()。
void start()
{
The data to be sent is stored in the class member message_
as we need to keep the data valid until the asynchronous operation is complete.
要發(fā)送的數(shù)據(jù)保存在類成員變量message_ 中,在異步操作完成前我們需要保證數(shù)據(jù)的有效性。

When initiating the asynchronous operation, and if using boost::bind(), you must specify only the arguments that match the handler's parameter list. In this program, both of the argument placeholders (boost::asio::placeholders::error and boost::asio::placeholders::bytes_transferred) could potentially have been removed, since they are not being used in handle_write()
.
當(dāng)啟動(dòng)一個(gè)異步操作時(shí),如果使用boost::bind(),你只需要指定一個(gè)符合句柄參數(shù)列表簽名的參數(shù)。在本例中,任何一個(gè)參數(shù)占位符(boost::asio::placeholders::error 和boost::asio::placeholders::bytes_transferred)皆可被隱式地移除,因?yàn)椴僮?font id=ga9. face="Courier New" goog_docs_charIndex="4205">write()并沒(méi)有使用它們。
boost::asio::async_write(socket_, boost::asio::buffer(message_),
boost::bind(&tcp_connection::handle_write, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
Any further actions for this client connection are now the responsibility of handle_write()
.
任何對(duì)客戶端連接的下一步操作都由handle_write()函數(shù)負(fù)責(zé)處理。
}
private:
tcp_connection(boost::asio::io_service& io_service)
: socket_(io_service)
{
}
void handle_write(const boost::system::error_code& /*error*/,
size_t /*bytes_transferred*/)
{
}
tcp::socket socket_;
std::string message_;
};
Removing unused handler parameters
移除無(wú)用的操作參數(shù)
You may have noticed that the error
, and bytes_transferred
parameters are not used in the body of the handle_write()
function. If parameters are not needed, it is possible to remove them from the function so that it looks like:
你可能已經(jīng)注意到了:error和bytes_transferred 參數(shù)并沒(méi)有在 handle_write()
函數(shù)體內(nèi)被應(yīng)用。因此,如果參數(shù)并不是必須的,我們可以移除它們,如下所示:
void handle_write()
{
}
The boost::asio::async_write() call used to initiate the call can then be changed to just:
用來(lái)發(fā)起呼叫的boost::asio::async_write()函數(shù)通常可以被改寫成下面這樣:
boost::asio::async_write(socket_, boost::asio::buffer(message_),
boost::bind(&tcp_connection::handle_write, shared_from_this()));
See the full source listing
全部源碼:
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <ctime>
#include <iostream>
#include <string>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
class tcp_connection
: public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& io_service)
{
return pointer(new tcp_connection(io_service));
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
message_ = make_daytime_string();
boost::asio::async_write(socket_, boost::asio::buffer(message_),
boost::bind(&tcp_connection::handle_write, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
private:
tcp_connection(boost::asio::io_service& io_service)
: socket_(io_service)
{
}
void handle_write(const boost::system::error_code& /*error*/,
size_t /*bytes_transferred*/)
{
}
tcp::socket socket_;
std::string message_;
};
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service)
: acceptor_(io_service, tcp::endpoint(tcp::v4(), 13))
{
start_accept();
}
private:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(acceptor_.io_service());
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
void handle_accept(tcp_connection::pointer new_connection,
const boost::system::error_code& error)
{
if (!error)
{
new_connection->start();
start_accept();
}
}
tcp::acceptor acceptor_;
};
int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server(io_service);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}