c++TCP和UDP编写一个简单的可传输文件的Client/Server网络应用程序
时间: 2024-10-17 18:14:04 浏览: 27
C++实现Socket编程[计算机网络实验].doc
在C++中编写一个既能通过TCP又能通过UDP传输文件的简单Client/Server网络应用需要分别处理这两种协议。下面是一个简化的例子,我们将分别展示TCP服务器接收文件和客户端发送文件的部分。
**TCP服务器 (FileReceiver.cpp)**
```cpp
#include <iostream>
#include <fstream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
class FileReceiver {
public:
void start_server(int port) {
try {
auto io_service = boost::asio::io_service();
server.listen(tcp::endpoint(tcp::v4(), port));
for (;;) {
tcp::socket socket(io_service);
server.accept(socket);
std::string filename;
std::getline(socket, filename); // 接收文件名
std::ifstream file(filename, std::ios::binary);
if (!file) {
std::cerr << "Failed to open file: " << filename << std::endl;
continue;
}
boost::array<char, 4096> buffer;
while (std::streamsize read_size = file.read(buffer.data(), sizeof(buffer))) {
socket.write(buffer.data(), read_size);
}
file.close();
std::cout << "Received file: " << filename << std::endl;
}
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
};
int main() {
FileReceiver fr;
fr.start_server(8080);
return 0;
}
```
**TCP客户端 (FileSender.cpp)**
```cpp
#include <iostream>
#include <fstream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
class FileSender {
public:
void send_file(const std::string& host, int port, const std::string& filename) {
try {
auto io_service = boost::asio::io_service();
tcp::resolver resolver(io_service);
tcp::resolver::query query(host, std::to_string(port));
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
std::ofstream file(filename, std::ios::binary);
if (!file) {
std::cerr << "Failed to open file: " << filename << std::endl;
return;
}
char buffer[4096];
std::ifstream source_file(filename, std::ios::binary);
while (source_file.read(buffer, sizeof(buffer))) {
socket.write(buffer, sizeof(buffer));
}
source_file.close();
std::cout << "Sent file: " << filename << std::endl;
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
};
int main() {
FileSender fs;
fs.send_file("localhost", 8080, "test.txt");
return 0;
}
```
阅读全文