Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Сети > Как передать по IP файл?


Автор: =Женек= 10.4.2012, 08:12
Господа есть задача.
В известной папке на одном компе лежит файл. Программа должна его передать на другой комп с ивзестным IP адресом, тоже в определенную папку. Если надо, то допускается установка отдельного приложения на компе приемнике файла. А в идеале хотелось бы просто расшарить эту папку.

В какую сторону смотреть? Пишу на C++ Builder, может есть какие VCL позволяющие легко решить эту задачу?

Спасибо.

Автор: Cheloveck 10.4.2012, 10:18
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363851%28v=vs.85%29.aspx
или
http://msdn.microsoft.com/en-us/library/windows/desktop/ms741416%28v=vs.85%29.aspx

Автор: =Женек= 10.4.2012, 10:25
спасибо за MSDN, но хотелось бы пример кода от людей, кто уже делал это.

Автор: igorrr37 29.4.2012, 08:54
на бустах писал так
client
Код

#include <iostream>
#include <fstream>
#include <string>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
#include <cinttypes>
#include <windows.h>
typedef boost::asio::ip::tcp tcp;
namespace fs = boost::filesystem3;

int main()
{
    SetConsoleOutputCP(1251);
    std::cout<<"Client is running\n";
    try{
        boost::asio::io_service io;
        tcp::socket sock(io);
        tcp::endpoint endPoint(boost::asio::ip::address::from_string("127.0.0.1"), 9090); // ip и порт сервера(принимает файл)
        boost::system::error_code ec;
        sock.connect(endPoint, ec);
        if(ec){ std::cerr << ec.message(); std::cin.get(); return __LINE__; }
        else std::cout<<"Connection established\n";
        std::cout << "Input file path\n";
        std::string filePath;
        std::getline(std::cin, filePath);
        std::ifstream ifs(filePath.c_str(), std::ios::binary);
        if(!ifs.is_open()){ std::cerr << "Can't read file\n"; std::cin.get(); return __LINE__; }
        std::uintmax_t fileSize = fs::file_size(fs::path(filePath));
        std::cout << "fileSize: " << fileSize << std::endl;
        std::size_t sentFileName = boost::asio::write(sock, boost::asio::buffer("FileName: " + fs::path(filePath).filename().string() + "\r\n"));
        std::size_t sentFileSize = boost::asio::write(sock, boost::asio::buffer("FileSize: " + boost::lexical_cast<std::string>(fileSize) + "\r\n\r\n"));
        std::uintmax_t sentFileBody = 0;
        char fileBuf[10000];
        std::size_t fileBufSize = sizeof(fileBuf);
        while(ifs)
        {
            ifs.read(fileBuf, fileBufSize);
            sentFileBody += boost::asio::write(sock, boost::asio::buffer(fileBuf, ifs.gcount()));
        }
        if(sentFileBody != fileSize){std::cerr << "write() failed\n"; std::cin.get(); return __LINE__;}
        std::cout << "sentFileName: " << sentFileName << std::endl
        << "sentFileSize: " << sentFileSize << std::endl
        << "sentFileBody: " << sentFileBody << std::endl;
        std::cout << "OK" << std::endl;
        ifs.close();
        if(sock.shutdown(tcp::socket::shutdown_both, ec))
        {
            std::cerr << "shutdown() failed: " << ec.message() << std::endl;
        }
        sock.close();
    }
    catch(std::exception const& ex)
    {
        std::cerr << "Exception: " << ex.what() << std::endl;
    }
    std::cin.get();
    return 0;
}

server
Код
#include <iostream>
#include <string>
#include <fstream>
#include <boost/asio.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <windows.h>
typedef boost::asio::ip::tcp tcp;

boost::smatch res;
boost::regex regFileName("FileName: *(.+?)\r\n");
boost::regex regFileSize("FileSize: *([0-9]+?)\r\n");

int main (){
    SetConsoleOutputCP(1251);
    std::cout<<"Server is running\n";
    try{
        boost::asio::io_service io;
        tcp::socket sock(io);
        boost::system::error_code ec;
        tcp::acceptor acc(io, tcp::endpoint(tcp::v4(), 9090));
        acc.accept(sock);
        std::cout << "Client has been accepted\n";
        boost::asio::streambuf sBuf;;
        std::istream istr(&sBuf);
        std::size_t l = boost::asio::read_until(sock, sBuf, boost::regex("(?:\r\n){2,}"), ec);
        if(ec){std::cerr << "read_until failed\nl = " << l <<"\n"; std::cin.get(); return __LINE__;}
        std::string headers, tmp;
        while(std::getline(istr, tmp) && tmp != "\r")
        {
            headers += (tmp + '\n');
        }
        std::cout << "Headers:\n" << headers << std::endl;
        if(!boost::regex_search(headers, res, regFileSize))
        {
            std::cerr << "regFileSize not found\n";
            std::cin.get();
            return __LINE__;
        }
        std::size_t fileSize = boost::lexical_cast<std::size_t>(res[1]);
        std::cout << "fileSize: " << fileSize << std::endl;
        if(!boost::regex_search(headers, res, regFileName))
        {
            std::cerr << "regFileName not found\n";
            std::cin.get();
            return __LINE__;
        }
        std::string fileName = res[1];
        std::cout << "fileName is " << fileName << std::endl;
        std::ofstream ofs(("c:\\" + fileName).c_str(), std::ios::binary); // файл сохраняется на диск C
        if(!ofs.is_open()){std::cerr << "Can't create file\n"; std::cin.get(); return __LINE__;}
        std::size_t len = 0;
        std::cout << "sBuf.size() = " << sBuf.size() << std::endl;
        if(sBuf.size())
        {
            len += sBuf.size();
            ofs << &sBuf;
        }
        while(len != fileSize)
        {
            len += boost::asio::read(sock, sBuf, boost::asio::transfer_at_least(1));
            ofs << &sBuf;
            std::cout << "len: " << len << std::endl;
        }
        std::cout << "OK" << std::endl;
        ofs.close();
        if(sock.shutdown(tcp::socket::shutdown_both, ec))
        {
            std::cerr << "shutdown() failed: " << ec.message() << std::endl;
        }
        sock.close();
        acc.close();
    }
    catch(std::exception const& ex)
    {
        std::cerr << "Exception: " << ex.what() << std::endl;
    }
    std::cin.get();
    return 0;
}

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)