0

有没有办法使用 tcp 检查非 boost asio 程序中的错误?有没有办法随机向连接添加错误?我用 C++ 制作了一个简单的 Echo 服务器,现在我必须生成随机错误,但问题是我不知道如何。

或者如果这有更多帮助,我需要检查二维奇偶校验(DATA、ACK、NAK)。

希望您能够帮助我。

客户:

#include <iostream>
#include <asio\include\asio.hpp>
#include <spdlog\spdlog.h>

using namespace std;
using namespace asio;
using namespace asio::ip;

auto console = spdlog::stderr_logger_st("console");

void usage(){
    console->error("invalid argument exception");
    cout << "usage: tcp_client [port]" << endl;
    cout << "usage: tcp_client [host] [port]" << endl;
}

void connectServer(string host, string port){
    tcp::iostream strm{ host, port };
    if (strm){
        cout << "Bitte Text eingeben: ";
        string input;
        getline(cin, input);
        strm << input << endl;
        console->info("Client sent to Server: " + input);
        string data;
        getline(strm, data);
        console->info("Response from Server: " + data);
        strm.close();
    }
    else{
    cout << "no connection to server on " + host + " using port: " +  port << endl;
    }
}

int main(int argc, char* argv[]){
    if (argc == 1){
        usage();
    }
    else if (argc == 2){
        string port = argv[1];
        connectServer("localhost",port);
    }
    else if (argc == 3){
        string host = argv[1];
        string port = argv[2];
        connectServer(host, port);
    }
    else{
        usage();
    }
}

服务器:

#include <iostream> 
#include <asio\include\asio.hpp>
#include <spdlog\spdlog.h>

using namespace std; 
using namespace asio::ip;

auto console = spdlog::stderr_logger_st("console");

void usage(){
    console->error("invalid argument exception");
    cout << "usage: tcp_server [port]" << endl;
}

void responseClient(unsigned short port){
    asio::io_context ctx;
    tcp::endpoint ep{ tcp::v4(), port };
    tcp::acceptor acceptor{ ctx, ep};
    acceptor.listen();
    tcp::iostream strm;
    acceptor.accept(*strm.rdbuf());
    string data;
    getline(strm, data);
    console->alert("Request from Client: " + data);
    strm << data;
    console->alert("Response to Client: " + data);
    strm.close();
    console->alert("Closing stream");
}

int main(int argc, char* argv[]) {
    if (argc == 1){
        usage();
    }
    else if (argc == 2){
        unsigned short port = stoi(argv[1]);
        responseClient(port);
    }
}
4

0 回答 0