Created
January 9, 2025 04:20
-
-
Save edxmorgan/39af2ec7b8d3734a23a2046f84984958 to your computer and use it in GitHub Desktop.
a simple dvl-a50 tcp cpp client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <boost/asio.hpp> | |
#include "json.hpp" // Changed from <nlohmann/json.hpp> to "json.hpp" | |
using boost::asio::ip::tcp; | |
using json = nlohmann::json; | |
// Function to handle received JSON data | |
void handle_json(const json& data) { | |
std::cout << "Received JSON data:\n" << data.dump(4) << std::endl; | |
} | |
int main() { | |
// Server details | |
std::string host = "192.168.2.95"; | |
int port = 16171; | |
try { | |
// Create an IO context | |
boost::asio::io_context io_context; | |
// Resolve the host and port | |
tcp::resolver resolver(io_context); | |
tcp::resolver::results_type endpoints = resolver.resolve(host, std::to_string(port)); | |
// Create and connect the socket | |
tcp::socket socket(io_context); | |
std::cout << "Connecting to " << host << ":" << port << "..." << std::endl; | |
boost::asio::connect(socket, endpoints); | |
std::cout << "Connected successfully." << std::endl; | |
// Buffer to store incoming data | |
boost::asio::streambuf buffer; | |
std::string data_buffer; | |
while (true) { | |
// Read until newline | |
boost::system::error_code error; | |
std::size_t bytes_transferred = boost::asio::read_until(socket, buffer, '\n', error); | |
if (error) { | |
if (error == boost::asio::error::eof) { | |
std::cout << "No more data received. Closing connection." << std::endl; | |
} else { | |
std::cerr << "Error while reading: " << error.message() << std::endl; | |
} | |
break; | |
} | |
// Convert buffer to string | |
std::istream is(&buffer); | |
std::string line; | |
std::getline(is, line); | |
// Ignore empty lines | |
if (line.empty()) { | |
continue; | |
} | |
try { | |
// Parse JSON | |
json json_data = json::parse(line); | |
handle_json(json_data); | |
} catch (json::parse_error& e) { | |
std::cerr << "Failed to decode JSON: " << e.what() << std::endl; | |
std::cerr << "Received line: " << line << std::endl; | |
} | |
} | |
// Socket is closed automatically when it goes out of scope | |
} catch (std::exception& e) { | |
std::cerr << "An error occurred: " << e.what() << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment