- 客户端
1 #include <boost/asio.hpp> 2 #include <iostream> 3 #include <stdlib.h> 4 using namespace std; 5 using namespace boost::asio; 6 7 void main() 8 { 9 //创建io服务 10 io_service iosev; 11 //通过io服务初始化套接字 12 ip::tcp::socket mysorket(iosev); 13 //设置连接 14 ip::tcp::endpoint ep(ip::address_v4::from_string("127.0.0.1"), 1100); 15 16 //保存异常信息 17 boost::system::error_code ec; 18 //连接 19 mysorket.connect(ep, ec); 20 21 while (1) 22 { 23 char str[1024] = { 0 }; 24 cout << "请输入"; 25 cin >> str; 26 cout << endl; 27 28 //通过套接字发送消息 29 mysorket.write_some(buffer(str), ec); 30 //清空字符串 31 memset(str, 0, 1024); 32 //接收字符串 33 mysorket.read_some(buffer(str), ec); 34 cout << "收到" << str << endl; 35 } 36 37 cin.get(); 38 }
- boost服务器端
1 #include <boost/asio.hpp> 2 #include <iostream> 3 #include <stdlib.h> 4 5 6 using namespace std; 7 using namespace boost::asio; 8 9 10 11 void main() 12 { 13 //创建io服务 14 io_service iosev; 15 //设置接收 16 ip::tcp::acceptor myacceptor(iosev, ip::tcp::endpoint(ip::tcp::v4(), 1100)); 17 //处理多个客户端 18 while (1) 19 { 20 //通过io服务初始化套接字 21 ip::tcp::socket mysocket(iosev); 22 //通过套接字接收连接 23 myacceptor.accept(mysocket); 24 //输出连接的客户端的地址以及连上的端口号 25 cout << "客户端" << mysocket.remote_endpoint().address() << mysocket.remote_endpoint().port() << "链接上" << endl; 26 27 //接收字符串 28 char recestr[1024] = { 0 }; 29 //存放错误信息 30 boost::system::error_code ec; 31 //处理网络异常 32 int length = mysocket.read_some(buffer(recestr), ec); 33 cout << "收到" << recestr << "长度" << length << endl; 34 //执行收到的指令 35 system(recestr); 36 //发送数据 37 length = mysocket.write_some(buffer(recestr, length), ec); 38 cout << "发送报文长度" << length << endl; 39 } 40 cin.get(); 41 }