1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| int main(int argc, char **argv) { try {
boost::asio::io_context io_context; tcp::socket sock(io_context); boost::asio::ip::address TargetIp; string FilenameOrMsg; string &FileName = FilenameOrMsg; string &Msg = FilenameOrMsg; int Is_File = 0; if (Parameter_parsing(argc, argv, FilenameOrMsg, Is_File, TargetIp) == Error) { cout << "Usage: ./send <ip> <filename or message>" << endl; return -1; } sock.connect(tcp::endpoint(TargetIp, PORT)); if (Is_File) { string _FileSize = std::to_string(std::filesystem::file_size(FileName)); string _FileName = filesystem::path(FilenameOrMsg).filename().string(); string _info = _FileName + '|' + _FileSize; size_t _info_Size = _info.size(); char _info_Size_buffer[sizeof(size_t)]; memcpy(_info_Size_buffer, &_info_Size, sizeof(size_t)); char Mode[10] = "FILE MODE"; sock.send(boost::asio::buffer(Mode, 10)); sock.send(boost::asio::buffer(_info_Size_buffer, sizeof(size_t))); sock.send(boost::asio::buffer(_info, _info_Size)); } else { char Mode[10] = "MSGS MODE"; sock.send(boost::asio::buffer(Mode, 10)); size_t _Msg_Size = Msg.size(); char _Msg_Size_buffer[sizeof(size_t)]; memcpy(_Msg_Size_buffer, &_Msg_Size, sizeof(size_t)); int len = sock.send(boost::asio::buffer(_Msg_Size_buffer, sizeof(size_t))); } char confirm_send = 0; sock.read_some(boost::asio::buffer(&confirm_send, sizeof(char))); if (Is_File) if (confirm_send || sock.is_open()) send_file(sock, FileName); else cout << "对方已拒绝接受文件!" << endl; else sock.send(boost::asio::buffer(Msg, Msg.size())); sock.close(); } catch (const boost::system::system_error &e) { cout << "无法链接至目标主机!" << '\n'; } return 0; }
|