#include <iostream> #include <string> #include <boost/asio.hpp> #include <boost/array.hpp>
using namespace boost::asio;
bool recv_remote_file(ip::tcp::socket *socket, std::string remote_file_path, std::string local_file_path) { boost::system::error_code error_code;
std::string message = remote_file_path; bool ref = (*socket).write_some(boost::asio::buffer(message), error_code); if (ref == false) return false;
char buffer[1024] = { 0 };
FILE * fp = fopen(local_file_path.c_str(), "wb"); if (NULL == fp) return false;
int length = 0;
while ((length = (*socket).read_some(boost::asio::buffer(buffer, 1024), error_code)) > 0) { if (strncmp(buffer, "goodbye lyshark",15) == 0) { std::cout << "传输结束,再见了 lyshark" << std::endl; fclose(fp); return true; }
if (fwrite(buffer, sizeof(char), length, fp) < length) { std::cout << "写入文件失败" << std::endl; break; } std::cout << "接收字节数: " << length << " Bytes" << std::endl; memset(buffer, 0, 1024); }
if (error_code) { fclose(fp); return false; } fclose(fp); return true; }
bool send_local_file(ip::tcp::socket *socket, std::string local_file_path, std::string remote_file_path) { boost::system::error_code ec; char buffer[1024] = { 0 };
bool ref = (*socket).write_some(boost::asio::buffer(remote_file_path)); if (ref == false) return false;
FILE * fp = fopen(local_file_path.c_str(), "rb"); if (NULL == fp) return false;
int length = 0;
while ((length = fread(buffer, sizeof(char), 1024, fp)) > 0) { bool ref = (*socket).write_some(boost::asio::buffer(buffer, 1024)); if (ref != false) { std::cout << "发送字节数: " << length << " Bytes" << std::endl; memset(buffer, 0, 1024); } }
(*socket).write_some(boost::asio::buffer("goodbye lyshark"));
if (ec) { fclose(fp); return false; } fclose(fp); return true; }
int main(int argc, char* argv[]) { io_service io_service; ip::tcp::acceptor acceptor(io_service, ip::tcp::endpoint(ip::tcp::v4(), 6666)); ip::tcp::socket socket(io_service); acceptor.accept(socket);
std::cout << "远端IP地址: " << socket.remote_endpoint().address() << std::endl; std::cout << "本端IP地址: " << socket.local_endpoint().address() << std::endl;
bool recv_ref = recv_remote_file(&socket, "c://lyshark.exe", "d://lyshark.exe"); std::cout << "下载状态: " << recv_ref << std::endl;
std::system("pause");
bool send_ref = send_local_file(&socket, "d://lyshark.exe", "c://test.exe"); std::cout << "上传状态: " << send_ref << std::endl;
std::system("pause"); return 0; }
|