同步socket例子
服务端
客户端
运行结果:
服务端:
server start...
0.0.0.0
cliend:127.0.0.1
客户端:
client start...
recive from 127.0.0.1
hello asio
服务端
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using namespace std;
int main() {
try
{
cout << "server start..." << endl;
boost::asio::io_service ios;
boost::asio::ip::tcp::acceptor acceptor(ios, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 6688));
cout << acceptor.local_endpoint().address() << endl;
while (true)
{
boost::asio::ip::tcp::socket sock(ios);
acceptor.accept(sock);
cout << "cliend:";
cout << sock.remote_endpoint().address() << endl;
sock.write_some(boost::asio::buffer("hello asio"));
}
}
catch(std::exception& e)
{
cout << e.what() << endl;
}
}
客户端
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <vector>
#include <boost/bind.hpp>
using namespace std;
int main() {
boost::asio::io_service ios;
cout << "client start..." << endl;
try
{
boost::asio::ip::tcp::socket sock(ios);
boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 6688);
sock.connect(ep);
vector<char> str(100, 0); // 定义一个vector缓冲区
sock.read_some(boost::asio::buffer(str)); // 使用buffer()包装缓冲区接收数据
cout << "recive from " << sock.remote_endpoint().address() << endl;
cout << &str[0] << endl;// 输出接收到的字符串
}
catch (std::exception& e)
{
cout << e.what() << endl;
}
ios.run();
return 0;
}
运行结果:
服务端:
server start...
0.0.0.0
cliend:127.0.0.1
客户端:
client start...
recive from 127.0.0.1
hello asio