mirror of
https://github.com/kierankihn/uno-game.git
synced 2025-12-27 02:13:18 +08:00
feat(network): add NetworkClient for TCP communication
- Introduced `NetworkClient` class for client-side TCP communication. - Implemented `connect`, `send`, and `read` methods for message handling. - Updated `CMakeLists.txt` to include `NetworkClient.cpp` in the build configuration.
This commit is contained in:
39
src/network/NetworkClient.cpp
Normal file
39
src/network/NetworkClient.cpp
Normal file
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @file NetworkClient.cpp
|
||||
*
|
||||
* @author Yuzhe Guo
|
||||
* @date 2025.11.28
|
||||
*/
|
||||
#include "NetworkClient.h"
|
||||
|
||||
#include <asio/connect.hpp>
|
||||
#include <asio/read.hpp>
|
||||
#include <asio/write.hpp>
|
||||
#include <utility>
|
||||
|
||||
namespace UNO::NETWORK {
|
||||
NetworkClient::NetworkClient(std::function<void(std::string)> callback) : socket_(io_context_), callback_(std::move(callback)) {}
|
||||
|
||||
void NetworkClient::connect(const std::string &host, uint16_t port)
|
||||
{
|
||||
asio::ip::tcp::resolver resolver(io_context_);
|
||||
auto endpoints = resolver.resolve(host, std::to_string(port));
|
||||
asio::connect(socket_, endpoints.begin(), endpoints.end());
|
||||
}
|
||||
|
||||
void NetworkClient::send(const std::string &message)
|
||||
{
|
||||
size_t length = message.size();
|
||||
asio::write(this->socket_, asio::buffer(&length, sizeof(length)));
|
||||
asio::write(this->socket_, asio::buffer(message));
|
||||
}
|
||||
|
||||
std::string NetworkClient::read()
|
||||
{
|
||||
size_t length;
|
||||
asio::read(this->socket_, asio::buffer(&length, sizeof(length)));
|
||||
std::vector<char> buffer(length);
|
||||
asio::read(this->socket_, asio::buffer(buffer));
|
||||
return {buffer.begin(), buffer.end()};
|
||||
}
|
||||
} // namespace UNO::NETWORK
|
||||
39
src/network/NetworkClient.h
Normal file
39
src/network/NetworkClient.h
Normal file
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @file NetworkClient.h
|
||||
*
|
||||
* @author Yuzhe Guo
|
||||
* @date 2025.11.28
|
||||
*/
|
||||
#pragma once
|
||||
#include <asio/io_context.hpp>
|
||||
#include <asio/ip/tcp.hpp>
|
||||
|
||||
namespace UNO::NETWORK {
|
||||
|
||||
class NetworkClient {
|
||||
private:
|
||||
asio::io_context io_context_;
|
||||
asio::ip::tcp::socket socket_;
|
||||
std::function<void(std::string)> callback_;
|
||||
|
||||
public:
|
||||
explicit NetworkClient(std::function<void(std::string)> callback);
|
||||
|
||||
/**
|
||||
* 连接到服务端
|
||||
* @param host 服务端地址
|
||||
* @param port 服务端端口
|
||||
*/
|
||||
void connect(const std::string &host, uint16_t port);
|
||||
|
||||
/**
|
||||
* 向服务端发送消息
|
||||
* @param message 要发送的消息
|
||||
*/
|
||||
void send(const std::string &message);
|
||||
|
||||
[[nodiscard]] std::string read();
|
||||
};
|
||||
|
||||
} // namespace UNO::NETWORK
|
||||
|
||||
Reference in New Issue
Block a user