forked from CPL/Simulator
107 lines
2.3 KiB
C++
107 lines
2.3 KiB
C++
#pragma once
|
|
|
|
#include "Client.h"
|
|
|
|
Client::Client(const char* ip, int port) : running(true), Connection(INVALID_SOCKET)
|
|
{
|
|
if (!ConnectToServer(ip, port))
|
|
{
|
|
std::cerr << "Failed to connect to server!" << std::endl;
|
|
}
|
|
}
|
|
|
|
Client::~Client()
|
|
{
|
|
Stop();
|
|
CloseConnection();
|
|
}
|
|
|
|
bool Client::ConnectToServer(const char* ip, int port)
|
|
{
|
|
WSAData wsaData;
|
|
WORD DLLVersion = MAKEWORD(2, 2);
|
|
|
|
if (WSAStartup(DLLVersion, &wsaData) != 0)
|
|
{
|
|
std::cerr << "Error: WSAStartup failed" << std::endl;
|
|
return false;
|
|
}
|
|
|
|
SOCKADDR_IN addr;
|
|
inet_pton(AF_INET, ip, &addr.sin_addr);
|
|
addr.sin_port = htons(port);
|
|
addr.sin_family = AF_INET;
|
|
|
|
Connection = socket(AF_INET, SOCK_STREAM, 0);
|
|
if (Connection == INVALID_SOCKET)
|
|
{
|
|
std::cerr << "Error: Failed to create socket" << std::endl;
|
|
WSACleanup();
|
|
return false;
|
|
}
|
|
|
|
if (connect(Connection, (SOCKADDR*)&addr, sizeof(addr)) != 0)
|
|
{
|
|
std::cerr << "Error: Failed to connect to server" << std::endl;
|
|
closesocket(Connection);
|
|
WSACleanup();
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
void Client::CloseConnection()
|
|
{
|
|
if (Connection != INVALID_SOCKET)
|
|
{
|
|
closesocket(Connection);
|
|
WSACleanup();
|
|
Connection = INVALID_SOCKET;
|
|
}
|
|
}
|
|
|
|
void Client::ReceiveHandler()
|
|
{
|
|
while (running)
|
|
{
|
|
DataIn tempData;
|
|
int result = recv(Connection, (char*)&tempData, sizeof(tempData), 0);
|
|
|
|
if (result <= 0)
|
|
{
|
|
std::cerr << "Error: Connection lost (recv failed)" << std::endl;
|
|
running = false;
|
|
break;
|
|
}
|
|
|
|
std::lock_guard<std::mutex> lock(dataMutex);
|
|
dataIn = tempData;
|
|
}
|
|
}
|
|
|
|
void Client::SendHandler()
|
|
{
|
|
while (running)
|
|
{
|
|
{
|
|
std::lock_guard<std::mutex> lock(dataMutex);
|
|
send(Connection, (char*)&dataOut, sizeof(dataOut), 0);
|
|
}
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
|
}
|
|
}
|
|
|
|
void Client::Start()
|
|
{
|
|
recvThread = std::thread(&Client::ReceiveHandler, this);
|
|
sendThread = std::thread(&Client::SendHandler, this);
|
|
}
|
|
|
|
void Client::Stop()
|
|
{
|
|
running = false;
|
|
if (recvThread.joinable()) recvThread.join();
|
|
if (sendThread.joinable()) sendThread.join();
|
|
}
|