Compare commits
5 Commits
a036846185
...
31fe531703
| Author | SHA1 | Date | |
|---|---|---|---|
| 31fe531703 | |||
| dcfb945c0b | |||
| fc65d4b146 | |||
| 78dd5366a0 | |||
| 8c5a2bd7ac |
@@ -100,7 +100,7 @@
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalDependencies>ws2_32.lib;SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
@@ -114,7 +114,7 @@
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalDependencies>ws2_32.lib;SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
@@ -132,7 +132,7 @@
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalDependencies>ws2_32.lib;SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
@@ -150,11 +150,15 @@
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalDependencies>ws2_32.lib;SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="Source.cpp" />
|
||||
<ClCompile Include="client.cpp" />
|
||||
<ClCompile Include="main.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="client.h" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
|
||||
@@ -15,8 +15,16 @@
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="Source.cpp">
|
||||
<ClCompile Include="client.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="main.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="client.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,2 +1,13 @@
|
||||
Source.cpp
|
||||
Client.vcxproj -> C:\Users\bartool\MyData\MyCode\Cpp\VisualStudio_lap\LanChat\Debug\Client.exe
|
||||
client.cpp
|
||||
main.cpp
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Client\client.cpp(216,26): warning C4244: 'initializing': conversion from 'std::streamoff' to 'size_t', possible loss of data
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Client\client.cpp(221,16): warning C4244: 'initializing': conversion from 'float' to 'int', possible loss of data
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Client\client.cpp(416,18): warning C4244: 'initializing': conversion from 'std::streamoff' to 'size_t', possible loss of data
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Client\client.cpp(462,20): warning C4018: '<': signed/unsigned mismatch
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Client\client.cpp(467,26): warning C4244: '+=': conversion from 'std::streamsize' to 'int', possible loss of data
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Client\client.cpp(468,27): warning C4244: 'argument': conversion from 'std::streamsize' to 'const unsigned int', possible loss of data
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Client\client.cpp(481,11): warning C4244: 'initializing': conversion from 'float' to 'int', possible loss of data
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Client\main.cpp(17,12): warning C4244: 'argument': conversion from 'time_t' to 'unsigned int', possible loss of data
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Client\client.cpp(76): warning C4715: 'Client::Initialize': not all control paths return a value
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Client\client.cpp(322): warning C4715: 'Client::CheckConnection': not all control paths return a value
|
||||
Client.vcxproj -> C:\MyCode\Cpp\VisualStudio_lap\LanChat\Debug\Client.exe
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,2 +1,2 @@
|
||||
#TargetFrameworkVersion=v4.0:PlatformToolSet=v142:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=10.0
|
||||
Debug|Win32|C:\Users\bartool\MyData\MyCode\Cpp\VisualStudio_lap\LanChat\|
|
||||
Debug|Win32|C:\MyCode\Cpp\VisualStudio_lap\LanChat\|
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,14 +0,0 @@
|
||||
//Client
|
||||
#include <SocketLibrary/SocketLibrary.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
int value = SocketLibrary::ReturnFive();
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
//(VC++ Directories) Add Include Dir -> Solution Dir
|
||||
//(VC++ Directories) Add Library Dir -> Output Dir
|
||||
//(Linket/Input) Add Additional Dep -> SocketLibrary.lib
|
||||
//(Solution/Project Build Order/Dependecies) Correct Oreder Build
|
||||
543
Client/client.cpp
Normal file
543
Client/client.cpp
Normal file
@@ -0,0 +1,543 @@
|
||||
//client
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <ctime>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include "client.h"
|
||||
|
||||
Result Client::Initialize(Endpoint ip)
|
||||
{
|
||||
connections.clear();
|
||||
FD_ZERO(&master_fd);
|
||||
|
||||
if (Network::Initialize())
|
||||
{
|
||||
// Winsock dziala
|
||||
std::cout << "[CLIENT] Winsock zostal poprawnie zainicjalizowany." << std::endl;
|
||||
|
||||
broadcastReciverUDP = Socket(Protocol::UDP_Reciver);
|
||||
if (broadcastReciverUDP.Create() == Result::Success)
|
||||
{
|
||||
// Socket do odebrania adresu serwara zostal utworzony
|
||||
std::cout << "[CLIENT] Gniazdo UDP do odnalezienia serwara zostalo utworzone." << std::endl;
|
||||
|
||||
if (broadcastReciverUDP.Bind(Endpoint("0.0.0.0", 54000)) == Result::Success)
|
||||
{
|
||||
// Socket UDP przypiety do portu
|
||||
std::cout << "[CLIENT] Gniazdo UDP zostalo przypisane do portu 54000" << std::endl;
|
||||
// Dodanie socketa do listy
|
||||
FD_SET(broadcastReciverUDP.GetSocket(), &master_fd);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
std::cerr << "[CLIENT] Nie udalo sie przypisac portu dla broadcastu UDP." << std::endl;
|
||||
broadcastReciverUDP.Close();
|
||||
return Result::Fail;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "[CLIENT] Nie moge utworzyc gniazda UDP." << std::endl;
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
listeningSocketTCP = Socket(Protocol::TCP);
|
||||
if (listeningSocketTCP.Create() == Result::Success)
|
||||
{
|
||||
// Socket listening zostal utworzony
|
||||
std::cout << "[CLIENT] Gniazdo TCP do nasluchu zostalo utworzone." << std::endl;
|
||||
|
||||
if (listeningSocketTCP.BindAndListen(ip) == Result::Success)
|
||||
{
|
||||
// Socket listening od teraz nasluchuje
|
||||
std::cout << "[SERVER] Gniazdo TCP do nasluchu nasluchuje." << std::endl;
|
||||
// Dodanie socketa do listy
|
||||
FD_SET(listeningSocketTCP.GetSocket(), &master_fd);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cerr << "[CLIENT] Nie udalo sie wlaczyc nasluchu na gniezdie TCP." << std::endl;
|
||||
listeningSocketTCP.Close();
|
||||
return Result::Fail;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cerr << "[CLIENT] Nie mozna utworzych gniazda TCP do nasluchu." << std::endl;
|
||||
return Result::Fail;
|
||||
}
|
||||
return Result::Success;
|
||||
}
|
||||
}
|
||||
|
||||
Result Client::CheckConnection()
|
||||
{
|
||||
fd_set copy_fd = master_fd;
|
||||
|
||||
int ConnectionCount = select(NULL, ©_fd, NULL, NULL, &waitTime);
|
||||
if (ConnectionCount)
|
||||
{
|
||||
if (ConnectionCount == SOCKET_ERROR)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("[SERVER] Problem z listening socket", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
for (int i = 0; i < ConnectionCount; i++)
|
||||
{
|
||||
if (copy_fd.fd_array[i] == listeningSocketTCP.GetSocket())
|
||||
{
|
||||
Socket newConnectionSocket(Protocol::TCP);
|
||||
//Endpoint newConnectionEndpoint();
|
||||
if (listeningSocketTCP.Accept(newConnectionSocket) == Result::Success)
|
||||
{
|
||||
struct clientInfo newClient;
|
||||
newClient.connection = newConnectionSocket;
|
||||
newClient.lastActiveTime = time(NULL);
|
||||
connections.push_back(newClient);
|
||||
//connections.push_back({newConnectionSocket, NULL, NULL, time(NULL)});
|
||||
FD_SET(newConnectionSocket.GetSocket(), &master_fd);
|
||||
//continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
//error
|
||||
}
|
||||
}
|
||||
|
||||
else if (copy_fd.fd_array[i] == broadcastReciverUDP.GetSocket())
|
||||
{
|
||||
std::string msg = "";
|
||||
int bytes = 0;
|
||||
broadcastReciverUDP.ReciveUDP(msg, bytes);
|
||||
//std::cout << "odebrano wiadosmosc broadcast o tresci: " << msg << std::endl;
|
||||
|
||||
std::string name, adress;
|
||||
unsigned short port;
|
||||
|
||||
std::replace(msg.begin(), msg.end(), ':', ' ');
|
||||
std::stringstream msgToParse(msg);
|
||||
|
||||
msgToParse >> name >> adress >> port;
|
||||
auto server = std::find_if(connections.begin(), connections.end(), [](clientInfo clientInfo) { return clientInfo.name == "server"; });
|
||||
if (server == connections.end())
|
||||
{
|
||||
Socket serverSocket(Protocol::TCP);
|
||||
Endpoint serverEnpoint(adress.c_str(), port);
|
||||
if (serverSocket.Create() == Result::Success)
|
||||
{
|
||||
|
||||
if (serverSocket.Connect(serverEnpoint) == Result::Success)
|
||||
{
|
||||
struct clientInfo newServer;
|
||||
newServer.connection = serverSocket;
|
||||
newServer.name = "server";
|
||||
newServer.listening = serverEnpoint;
|
||||
newServer.lastActiveTime = time(NULL);
|
||||
connections.push_back(newServer);
|
||||
FD_SET(serverSocket.GetSocket(), &master_fd);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
Message recived;
|
||||
std::string recivedMessage;
|
||||
int bytesRecived;
|
||||
|
||||
SOCKET lookingFor = copy_fd.fd_array[i];
|
||||
auto findedClient = std::find_if(connections.begin(), connections.end(), [lookingFor](clientInfo client) { return lookingFor == client.connection.GetSocket(); });
|
||||
|
||||
switch (findedClient->connection.ReciveAll(recivedMessage, bytesRecived))
|
||||
{
|
||||
case Result::Fail:
|
||||
case Result::ConnectionLost:
|
||||
FD_CLR(findedClient->connection.GetSocket(), &master_fd);
|
||||
findedClient->connection.Close();
|
||||
connections.erase(findedClient);
|
||||
break;
|
||||
|
||||
case Result::Success:
|
||||
//std::cout << "[" << bytesRecived << "] "<< recivedMessage << std::endl;
|
||||
|
||||
findedClient->lastActiveTime = time(NULL);
|
||||
if (recived.Parse(recivedMessage, bytesRecived) != Result::Success)
|
||||
{
|
||||
// wiadamosc niekompletna, bledna lub cos takiego
|
||||
if (writeFile_p.is_open())
|
||||
{
|
||||
writeFile_p.close();
|
||||
}
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
switch (recived.GetType())
|
||||
{
|
||||
case TypeOfMsg::Unknown:
|
||||
break;
|
||||
case TypeOfMsg::Text:
|
||||
{
|
||||
std::string name = recived.GetName();
|
||||
std::string msg = recived.GetMsg();
|
||||
if (findedClient->name != "server")
|
||||
{
|
||||
std::cout << "<" << name << "> " << msg << std::endl;
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "[" << name << "] " << msg << std::endl;
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
case TypeOfMsg::File:
|
||||
{
|
||||
|
||||
//std::ofstream writeFile(fileName, std::ios::binary | std::ios::trunc);
|
||||
if (!writeFile_p)
|
||||
{
|
||||
std::cout << "Nie udalo sie utworzyc pliku: " << fileName << std::endl;
|
||||
writeFile_p.close();
|
||||
}
|
||||
else
|
||||
{
|
||||
size_t totalSize = recived.GetTotalLenght();
|
||||
size_t recivedBytes = recived.GetLenght();
|
||||
writeFile_p.write(recived.GetMsg().c_str(), recivedBytes);
|
||||
size_t actualSize = writeFile_p.tellp();
|
||||
float percent = ((float)actualSize / totalSize);
|
||||
|
||||
int barWidth = 60;
|
||||
std::cout << "[";
|
||||
int pos = barWidth * percent;
|
||||
for (int i = 0; i < barWidth; ++i) {
|
||||
if (i < pos) std::cout << "=";
|
||||
else if (i == pos) std::cout << ">";
|
||||
else std::cout << " ";
|
||||
}
|
||||
std::cout << "] " << int(percent * 100.0) << " " <<std::setw(3) << "% " << actualSize << '\r';
|
||||
std::cout.flush();
|
||||
if (totalSize == actualSize)
|
||||
{
|
||||
writeFile_p.close();
|
||||
std::cout << std::endl;
|
||||
std::cout << "Odebralem plik " << fileName << std::endl;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
}
|
||||
case TypeOfMsg::Command:
|
||||
|
||||
switch (recived.GetCommand())
|
||||
{
|
||||
case Command::LogIn:
|
||||
{
|
||||
findedClient->name = recived.GetName();
|
||||
break;
|
||||
}
|
||||
case Command::LogOut:
|
||||
{
|
||||
std::string nameLogOut = recived.GetName();
|
||||
std::cout << nameLogOut << " wylogowal sie." << std::endl;
|
||||
auto connToDelete = std::find_if(connections.begin(), connections.end(), [nameLogOut](clientInfo client) {return nameLogOut == client.name; });
|
||||
if (connToDelete != connections.end())
|
||||
{
|
||||
FD_CLR(connToDelete->connection.GetSocket(), &master_fd);
|
||||
connToDelete->connection.Close();
|
||||
|
||||
connections.erase(connToDelete);
|
||||
}
|
||||
|
||||
auto availableClientToDelete = std::find_if(availableClients.begin(), availableClients.end(), [nameLogOut](clientInfo client) {return nameLogOut == client.name; });
|
||||
if (availableClientToDelete != availableClients.end())
|
||||
{
|
||||
availableClients.erase(availableClientToDelete);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Command::Adress:
|
||||
{
|
||||
int port = atoi(recived.GetMsg().c_str());
|
||||
Endpoint clientPortListenning = Endpoint(findedClient->connection.GetEndpoint().GetIpString().c_str(), (unsigned short)port);
|
||||
struct clientInfo newClient;
|
||||
newClient.listening = clientPortListenning;
|
||||
newClient.name = recived.GetName();
|
||||
availableClients.push_back(newClient);
|
||||
std::cout << newClient.name << " zalogowal sie." << std::endl;
|
||||
}
|
||||
break;
|
||||
case Command::ConnCheck:
|
||||
{
|
||||
Message msgConnCheck;
|
||||
std::string msg = msgConnCheck.PrepareCommand("", ownLogin, Command::ConnCheck);
|
||||
if (findedClient->connection.SendAll(msg.c_str(), msg.size()) != Result::Success)
|
||||
{
|
||||
//cos poszlo nie tak
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
case Command::FileName:
|
||||
{
|
||||
fileName = recived.GetFileName();
|
||||
fileName.insert(fileName.find('.'), "_reciv");
|
||||
|
||||
std::cout << "Uzytkownik " << recived.GetName() << " wysyla Ci plik " << fileName << std::endl;
|
||||
|
||||
writeFile_p = std::ofstream();
|
||||
writeFile_p.open(fileName, std::ios::binary | std::ios::trunc);
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
bool Client::isConnectedToSever()
|
||||
{
|
||||
if (connections.size() > 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Result Client::LoginToServer()
|
||||
{
|
||||
auto server = std::find_if(connections.begin(), connections.end(), [](clientInfo conn) { return conn.name == "server"; });
|
||||
if (server != connections.end())
|
||||
{
|
||||
Message addres;
|
||||
std::string port = std::to_string(listeningSocketTCP.GetEndpoint().GetPort());
|
||||
std::string msgAddres = addres.PrepareCommand(port, ownLogin, Command::Adress);
|
||||
if (server->connection.SendAll(msgAddres.c_str(), msgAddres.size()) != Result::Success)
|
||||
{
|
||||
// cos poszlo nie tak
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
Message login;
|
||||
std::string msgLogin = login.PrepareCommand("", ownLogin, Command::LogIn);
|
||||
if (server->connection.SendAll(msgLogin.c_str(), msgLogin.size()) != Result::Success)
|
||||
{
|
||||
// cos poszlo nie tak
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
}
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Client::SendMsg(std::string name, std::string msg)
|
||||
{
|
||||
Message msgToUser;
|
||||
std::string msgToSend = msgToUser.PrepareText(msg, ownLogin);
|
||||
|
||||
auto user = std::find_if(connections.begin(), connections.end(), [name](clientInfo client) {return client.name == name; });
|
||||
if (user != connections.end())
|
||||
{
|
||||
|
||||
user->connection.SendAll(msgToSend.c_str(), msgToSend.size());
|
||||
}
|
||||
else
|
||||
{
|
||||
auto userNotConn = std::find_if(availableClients.begin(), availableClients.end(), [name](clientInfo client) {return client.name == name; });
|
||||
if (userNotConn != availableClients.end())
|
||||
{
|
||||
Socket newClientSocket(Protocol::TCP);
|
||||
if (newClientSocket.Create() == Result::Success)
|
||||
{
|
||||
if (newClientSocket.Connect(userNotConn->listening) == Result::Success)
|
||||
{
|
||||
userNotConn->connection = newClientSocket;
|
||||
|
||||
connections.push_back(*userNotConn);
|
||||
FD_SET(newClientSocket.GetSocket(), &master_fd);
|
||||
|
||||
Message login;
|
||||
std::string msgLogin = login.PrepareCommand("", ownLogin, Command::LogIn);
|
||||
if (userNotConn->connection.SendAll(msgLogin.c_str(), msgLogin.size()) != Result::Success)
|
||||
{
|
||||
// cos poszlo nie tak
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
userNotConn->connection.SendAll(msgToSend.c_str(), msgToSend.size());
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Client::SendFile(std::string name, std::string filename)
|
||||
{
|
||||
auto user = std::find_if(connections.begin(), connections.end(), [name](clientInfo client) {return client.name == name; });
|
||||
|
||||
std::ifstream readFile("C:/test/"+filename, std::ios::binary | std::ios::ate);
|
||||
if (!readFile)
|
||||
{
|
||||
std::cout << "Nie udalo sie otworzyz pliku o nazwie: " << filename << std::endl;
|
||||
readFile.close();
|
||||
return Result::Fail;
|
||||
}
|
||||
std::cout << "Wysylam uzytkownikowi <" << name << "> plik " << filename << std::endl;
|
||||
size_t fileSize = readFile.tellg();
|
||||
readFile.seekg(0);
|
||||
char buffer[1025] = {};
|
||||
int bytesLeft = 0;
|
||||
|
||||
|
||||
Message prepareFile;
|
||||
std::string fileCmd = prepareFile.PrepareCommand(filename, ownLogin, Command::FileName);
|
||||
|
||||
if (user != connections.end())
|
||||
{
|
||||
user->connection.SendAll(fileCmd.c_str(), fileCmd.size());
|
||||
}
|
||||
else
|
||||
{
|
||||
auto userNotConn = std::find_if(availableClients.begin(), availableClients.end(), [name](clientInfo client) {return client.name == name; });
|
||||
if (userNotConn != availableClients.end())
|
||||
{
|
||||
Socket newClientSocket(Protocol::TCP);
|
||||
if (newClientSocket.Create() == Result::Success)
|
||||
{
|
||||
if (newClientSocket.Connect(userNotConn->listening) == Result::Success)
|
||||
{
|
||||
userNotConn->connection = newClientSocket;
|
||||
|
||||
connections.push_back(*userNotConn);
|
||||
FD_SET(newClientSocket.GetSocket(), &master_fd);
|
||||
|
||||
Message login;
|
||||
std::string msgLogin = login.PrepareCommand("", ownLogin, Command::LogIn);
|
||||
if (userNotConn->connection.SendAll(msgLogin.c_str(), msgLogin.size()) != Result::Success)
|
||||
{
|
||||
// cos poszlo nie tak
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
userNotConn->connection.SendAll(fileCmd.c_str(), fileCmd.size());
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
int bytes_sent = 0;
|
||||
auto userToSend = std::find_if(connections.begin(), connections.end(), [name](clientInfo client) {return client.name == name; });
|
||||
while (bytes_sent < fileSize)
|
||||
{
|
||||
|
||||
readFile.read(buffer, 1024);
|
||||
auto readBytes = readFile.gcount();
|
||||
bytes_sent += readBytes;
|
||||
std::string buf(buffer, readBytes);
|
||||
Message fileToSend;
|
||||
std::string msgToSend = fileToSend.PrepareFile(buf, ownLogin, fileSize);
|
||||
userToSend->connection.SendAll(msgToSend.c_str(), msgToSend.size());
|
||||
//auto bytesSent = readFile.gcount();
|
||||
|
||||
//auto actualPos = readFile.tellg();
|
||||
bytesLeft = fileSize - bytes_sent;
|
||||
//bytesLeft = fileSize - actualPos;
|
||||
float percent = (float)bytes_sent / fileSize;
|
||||
|
||||
int barWidth = 60;
|
||||
std::cout << "[";
|
||||
int pos = barWidth * percent;
|
||||
for (int i = 0; i < barWidth; ++i) {
|
||||
if (i < pos) std::cout << "=";
|
||||
else if (i == pos) std::cout << ">";
|
||||
else std::cout << " ";
|
||||
}
|
||||
std::cout << "] " << int(percent * 100.0) << " " << std::setw(3) << "% " << bytes_sent << '\r';
|
||||
std::cout.flush();
|
||||
}
|
||||
std::cout << std::endl;
|
||||
readFile.close();
|
||||
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Client::Input(std::string input)
|
||||
{
|
||||
std::string name, fileName, msg;
|
||||
if (input.at(0) == '@')
|
||||
{
|
||||
std::stringstream exp(input);
|
||||
exp.seekg(1);
|
||||
exp >> name;
|
||||
if (name.find('#') != std::string::npos)
|
||||
{
|
||||
std::replace(name.begin(), name.end(), '#', ' ');
|
||||
std::stringstream expcmd(name);
|
||||
expcmd >> name >> fileName;
|
||||
if (fileName != "")
|
||||
{
|
||||
//cos zrob
|
||||
SendFile(name, fileName);
|
||||
std::cout << fileName << " zostal wyslany." << std::endl;
|
||||
return Result::Success;
|
||||
}
|
||||
else
|
||||
{
|
||||
expcmd.seekg(1, std::ios_base::cur);
|
||||
std::getline(expcmd, msg);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
exp.seekg(1, std::ios_base::cur);
|
||||
std::getline(exp, msg);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
name = "server";
|
||||
msg = input;
|
||||
}
|
||||
|
||||
SendMsg(name, msg);
|
||||
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
//(VC++ Directories) Add Include Dir -> Solution Dir
|
||||
//(VC++ Directories) Add Library Dir -> Output Dir
|
||||
//(Linket/Input) Add Additional Dep -> SocketLibrary.lib
|
||||
//(Solution/Project Build Order/Dependecies) Correct Oreder Build
|
||||
//(Linker/Input) Add Additional Dep -> ws2_32.lib
|
||||
42
Client/client.h
Normal file
42
Client/client.h
Normal file
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
#include <vector>
|
||||
#include <fstream>
|
||||
#include <SocketLibrary/SocketLibrary.h>
|
||||
|
||||
using namespace SocketLibrary;
|
||||
|
||||
class Client
|
||||
{
|
||||
struct clientInfo {
|
||||
Socket connection;
|
||||
Endpoint listening;
|
||||
std::string name;
|
||||
time_t lastActiveTime;
|
||||
|
||||
};
|
||||
|
||||
public:
|
||||
Result Initialize(Endpoint ip);
|
||||
Result CheckConnection();
|
||||
bool isConnectedToSever();
|
||||
Result LoginToServer();
|
||||
Result SendMsg(std::string name, std::string msg);
|
||||
Result SendFile(std::string name, std::string filename);
|
||||
Result Input(std::string input);
|
||||
|
||||
private:
|
||||
Result SendFile();
|
||||
Socket listeningSocketTCP;
|
||||
Socket broadcastReciverUDP;
|
||||
std::vector<clientInfo> connections;
|
||||
std::vector<clientInfo> availableClients;
|
||||
|
||||
// std::vector<Connection> connections;
|
||||
fd_set master_fd;
|
||||
timeval waitTime = { 0, 1000 };
|
||||
Endpoint ownEndpoint;
|
||||
std::string fileName;
|
||||
std::ofstream writeFile_p;
|
||||
public:
|
||||
std::string ownLogin;
|
||||
};
|
||||
100
Client/main.cpp
Normal file
100
Client/main.cpp
Normal file
@@ -0,0 +1,100 @@
|
||||
#include "client.h"
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
#include <iostream>
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
|
||||
std::string GetLineFromCin() {
|
||||
std::string line;
|
||||
std::getline(std::cin, line);
|
||||
return line;
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
srand(time(NULL));
|
||||
unsigned short randomPort = rand() % 100 + 52000;
|
||||
Client client;
|
||||
|
||||
auto future = std::async(std::launch::async, GetLineFromCin);
|
||||
|
||||
time_t last_time = time(NULL);
|
||||
|
||||
if (client.Initialize(Endpoint("127.0.0.1", randomPort)) == Result::Success)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
client.CheckConnection();
|
||||
if (client.isConnectedToSever())
|
||||
{
|
||||
if (client.ownLogin == "")
|
||||
{
|
||||
std::cout << "Podaj Login: ";
|
||||
//std::getline(std::cin, client.ownLogin);
|
||||
client.ownLogin = future.get();
|
||||
client.LoginToServer();
|
||||
future = std::async(std::launch::async, GetLineFromCin);
|
||||
}
|
||||
|
||||
|
||||
if (future.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
|
||||
{
|
||||
auto line = future.get();
|
||||
client.Input(line);
|
||||
future = std::async(std::launch::async, GetLineFromCin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//using namespace SocketLibrary;
|
||||
//
|
||||
//int main()
|
||||
//{
|
||||
// if (Network::Initialize() == true)
|
||||
// {
|
||||
// Log::Print("[CLIENT] Winsok zostal zainicjolizowany. Mozemy dzialac.");
|
||||
// Socket socket;
|
||||
// if (socket.Create() == Result::Success)
|
||||
// {
|
||||
// Log::Print("[CLIENT] Utworzylem socket.");
|
||||
// if (socket.Connect(Endpoint("127.0.0.1", 53000)) == Result::Success)
|
||||
// {
|
||||
// Log::Print("[CLIENT] Polaczylem sie serverem.");
|
||||
// std::string outString = "Wysylam z klienta.";
|
||||
// char buffer[256];
|
||||
// strcpy_s(buffer, "witam z klienta!\0");
|
||||
// char c = NULL;
|
||||
// while (true)
|
||||
// {
|
||||
// socket.SendAll(outString.data(), outString.size());
|
||||
// //socket.SendAll(buffer, 256);
|
||||
// std::cout << "wyslalem: " << outString << std::endl;
|
||||
// std::string inString = "";
|
||||
// int bytesRecived = 0;
|
||||
// socket.ReciveAll(inString, bytesRecived);
|
||||
// std::cout << "Odebralem [" << bytesRecived << "]: " << inString << std::endl;
|
||||
// //char d = std::getchar();
|
||||
// /*if (d == 'q')
|
||||
// {
|
||||
// break;
|
||||
// }*/
|
||||
// Sleep(1000);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// socket.Close();
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//
|
||||
// Network::Shutdown();
|
||||
// system("pause");
|
||||
// return 0;
|
||||
//}
|
||||
30243
Client/tes_recivt.pdf
Normal file
30243
Client/tes_recivt.pdf
Normal file
File diff suppressed because one or more lines are too long
1
Client/tes_recivt.txt
Normal file
1
Client/tes_recivt.txt
Normal file
File diff suppressed because one or more lines are too long
30243
Client/test_reciv.pdf
Normal file
30243
Client/test_reciv.pdf
Normal file
File diff suppressed because one or more lines are too long
BIN
Debug/Client.exe
BIN
Debug/Client.exe
Binary file not shown.
BIN
Debug/Client.ilk
BIN
Debug/Client.ilk
Binary file not shown.
BIN
Debug/Client.pdb
BIN
Debug/Client.pdb
Binary file not shown.
BIN
Debug/Server.exe
BIN
Debug/Server.exe
Binary file not shown.
BIN
Debug/Server.ilk
BIN
Debug/Server.ilk
Binary file not shown.
BIN
Debug/Server.pdb
BIN
Debug/Server.pdb
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,14 +1,13 @@
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\vc142.pdb
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\vc142.idb
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\source.obj
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\debug\server.pdb
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\cl.command.1.tlog
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\cl.read.1.tlog
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\cl.write.1.tlog
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\link-cvtres.read.1.tlog
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\link-cvtres.write.1.tlog
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\link-rc.read.1.tlog
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\link-rc.write.1.tlog
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\link.command.1.tlog
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\link.read.1.tlog
|
||||
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\link.write.1.tlog
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.obj
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\server\debug\main.obj
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\server\debug\vc142.pdb
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\debug\server.ilk
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\debug\server.exe
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\debug\server.pdb
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\server\debug\vc142.idb
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\cl.36980.write.1.tlog
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\cl.command.1.tlog
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\cl.read.1.tlog
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\link.command.1.tlog
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\link.read.1.tlog
|
||||
c:\mycode\cpp\visualstudio_lap\lanchat\server\debug\server.tlog\link.write.1.tlog
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
Source.cpp
|
||||
Server.vcxproj -> C:\Users\bartool\MyData\MyCode\Cpp\VisualStudio_lap\LanChat\Debug\Server.exe
|
||||
main.cpp
|
||||
server.cpp
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\Server\server.cpp(328): warning C4715: 'Server::IncomingConnection': not all control paths return a value
|
||||
Server.vcxproj -> C:\MyCode\Cpp\VisualStudio_lap\LanChat\Debug\Server.exe
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,2 +1,2 @@
|
||||
#TargetFrameworkVersion=v4.0:PlatformToolSet=v142:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=10.0
|
||||
Debug|Win32|C:\Users\bartool\MyData\MyCode\Cpp\VisualStudio_lap\LanChat\|
|
||||
Debug|Win32|C:\MyCode\Cpp\VisualStudio_lap\LanChat\|
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
30
Server/Server.h
Normal file
30
Server/Server.h
Normal file
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
#include <vector>
|
||||
#include <SocketLibrary/SocketLibrary.h>
|
||||
|
||||
using namespace SocketLibrary;
|
||||
|
||||
class Server
|
||||
{
|
||||
struct clientInfo {
|
||||
Socket connection;
|
||||
Endpoint listening;
|
||||
std::string name;
|
||||
time_t lastActiveTime;
|
||||
};
|
||||
public:
|
||||
Result Initialize(Endpoint ip);
|
||||
Result IncomingConnection();
|
||||
Result CheckConnection();
|
||||
Result SendToClients();
|
||||
private:
|
||||
Socket listeningSocketTCP;
|
||||
Socket broadcastSenderUDP;
|
||||
std::vector<clientInfo> connections;
|
||||
|
||||
fd_set master_fd;
|
||||
timeval waitTime = { 0, 1000 };
|
||||
Endpoint ownEndpoint;
|
||||
public:
|
||||
bool sendUDP = true;
|
||||
};
|
||||
@@ -100,7 +100,7 @@
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalDependencies>ws2_32.lib;SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
@@ -114,7 +114,7 @@
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalDependencies>ws2_32.lib;SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
@@ -132,7 +132,7 @@
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalDependencies>ws2_32.lib;SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
@@ -150,11 +150,15 @@
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalDependencies>ws2_32.lib;SocketLibrary.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="Source.cpp" />
|
||||
<ClCompile Include="main.cpp" />
|
||||
<ClCompile Include="server.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="Server.h" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
|
||||
@@ -15,8 +15,16 @@
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="Source.cpp">
|
||||
<ClCompile Include="server.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="main.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="Server.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,7 +0,0 @@
|
||||
//Server
|
||||
#include <SocketLibrary/SocketLibrary.h>
|
||||
int main()
|
||||
{
|
||||
int value = SocketLibrary::ReturnFive();
|
||||
return 0;
|
||||
}
|
||||
89
Server/main.cpp
Normal file
89
Server/main.cpp
Normal file
@@ -0,0 +1,89 @@
|
||||
#include <ctime>
|
||||
#include "Server.h"
|
||||
|
||||
using namespace SocketLibrary;
|
||||
|
||||
int main()
|
||||
{
|
||||
Server server;
|
||||
server.Initialize(Endpoint("127.0.0.1", 53000));
|
||||
|
||||
|
||||
time_t last_time = time(NULL);
|
||||
|
||||
while (true)
|
||||
{
|
||||
server.IncomingConnection();
|
||||
if (last_time + 10 < time(NULL))
|
||||
{
|
||||
server.CheckConnection();
|
||||
last_time = time(NULL);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//using namespace SocketLibrary;
|
||||
//
|
||||
//int main()
|
||||
//{
|
||||
// if (Network::Initialize() == true)
|
||||
// {
|
||||
// Log::Print("[SERVER] Winsok zostal zainicjolizowany. Mozemy dzialac.");
|
||||
//
|
||||
//
|
||||
// Socket socketTCP(Protocol::TCP);
|
||||
// Socket socketUDP(Protocol::UDP);
|
||||
// if (socketTCP.Create() == Result::Success)
|
||||
// {
|
||||
// socketUDP.Create();
|
||||
// socketUDP.Bind(Endpoint("0.0.0.0", 54001));
|
||||
// Log::Print("[SERVER] Utworzylem gniazdo.");
|
||||
// if (socketTCP.BindAndListen(Endpoint("127.0.0.1", 54000), 5) == Result::Success)
|
||||
// {
|
||||
//
|
||||
//
|
||||
//
|
||||
// Socket newConnection;
|
||||
//
|
||||
//
|
||||
//
|
||||
// Log::Print("[SERVER] sukces");
|
||||
//
|
||||
//
|
||||
// if (socketTCP.Accept(newConnection) == Result::Success)
|
||||
// {
|
||||
// Log::Print("[SERVER] accept: sukces");
|
||||
// std::string buffer = "";
|
||||
// int size = 0;
|
||||
// while (true)
|
||||
// {
|
||||
//
|
||||
// newConnection.ReciveAll(buffer, size);
|
||||
// std::cout << "[" << size << "] " << buffer << std::endl;
|
||||
// buffer = "";
|
||||
// }
|
||||
// newConnection.Close();
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// Log::PrintError("[SERVER] accept: porazka", -1);
|
||||
// }
|
||||
// }
|
||||
// socketTCP.Close();
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// Log::PrintError("[SERVER] porazka", -1);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//
|
||||
// Network::Shutdown();
|
||||
// return 0;
|
||||
//}
|
||||
382
Server/server.cpp
Normal file
382
Server/server.cpp
Normal file
@@ -0,0 +1,382 @@
|
||||
//Server
|
||||
//#include <SocketLibrary/SocketLibrary.h>
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
#include <iomanip>
|
||||
|
||||
#include "Server.h"
|
||||
|
||||
|
||||
//(VC++ Directories) Add Include Dir -> Solution Dir
|
||||
//(VC++ Directories) Add Library Dir -> Output Dir
|
||||
//(Linket/Input) Add Additional Dep -> SocketLibrary.lib
|
||||
//(Solution/Project Build Order/Dependecies) Correct Oreder Build
|
||||
//(Linker/Input) Add Additional Dep -> ws2_32.lib
|
||||
|
||||
Result Server::Initialize(Endpoint ip)
|
||||
{
|
||||
connections.clear();
|
||||
FD_ZERO(&master_fd);
|
||||
ownEndpoint = ip;
|
||||
|
||||
if (Network::Initialize())
|
||||
{
|
||||
// Winsock dziala
|
||||
std::cout << "[SERVER] Winsock zostal poprawnie zainicjalizowany." << std::endl;
|
||||
|
||||
listeningSocketTCP = Socket(Protocol::TCP);
|
||||
if (listeningSocketTCP.Create() == Result::Success)
|
||||
{
|
||||
// Socket listening zostal utworzony
|
||||
std::cout << "[SERVER] Gniazdo TCP do nasluchu zostalo utworzone." << std::endl;
|
||||
|
||||
if (listeningSocketTCP.BindAndListen(ownEndpoint) == Result::Success)
|
||||
{
|
||||
// Socket listening od teraz nasluchuje
|
||||
std::cout << "[SERVER] Gniazdo TCP do nasluchu nasluchuje." << std::endl;
|
||||
// Dodanie socketa do listy
|
||||
FD_SET(listeningSocketTCP.GetSocket(), &master_fd);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cerr << "[SERVER] Nie udalo sie wlaczyc nasluchu na gniezdie TCP." << std::endl;
|
||||
listeningSocketTCP.Close();
|
||||
return Result::Fail;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cerr << "[SERVER] Nie mozna utworzych gniazda TCP do nasluchu." << std::endl;
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
broadcastSenderUDP = Socket(Protocol::UDP_Sender);
|
||||
if (broadcastSenderUDP.Create() == Result::Success)
|
||||
{
|
||||
// Socket zostal utworzony
|
||||
std::cout << "[SERVER] Gniazdo UDP do informowania zostalo utworzone." << std::endl;
|
||||
|
||||
// TODO - udp
|
||||
if (broadcastSenderUDP.AssignEndpoint(Endpoint("255.255.255.255", 54000)) == Result::Fail)
|
||||
{
|
||||
// error
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cerr << "[SERVER] Nie mozna utworzych gniazda UDP do broadcastu." << std::endl;
|
||||
return Result::Fail;
|
||||
}
|
||||
}
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Server::IncomingConnection()
|
||||
{
|
||||
//Sleep(1000);
|
||||
|
||||
fd_set copy_fd = master_fd;
|
||||
|
||||
int ConnectionCount = select(NULL, ©_fd, NULL, NULL, &waitTime);
|
||||
if (ConnectionCount)
|
||||
{
|
||||
if (ConnectionCount == SOCKET_ERROR)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("[SERVER] Problem z listening socket", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
for (int i = 0; i < ConnectionCount; i++)
|
||||
{
|
||||
if (copy_fd.fd_array[i] == listeningSocketTCP.GetSocket())
|
||||
{
|
||||
Socket newConnectionSocket(Protocol::TCP);
|
||||
//Endpoint newConnectionEndpoint();
|
||||
if (listeningSocketTCP.Accept(newConnectionSocket) == Result::Success )
|
||||
{
|
||||
struct clientInfo newClient;
|
||||
newClient.connection = newConnectionSocket;
|
||||
newClient.lastActiveTime = time(NULL);
|
||||
connections.push_back(newClient);
|
||||
//connections.push_back({newConnectionSocket, NULL, NULL, time(NULL)});
|
||||
FD_SET(newConnectionSocket.GetSocket(), &master_fd);
|
||||
//continue;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
//error
|
||||
}
|
||||
}
|
||||
|
||||
else if (copy_fd.fd_array[i] == broadcastSenderUDP.GetSocket())
|
||||
{
|
||||
// TODO
|
||||
//continue;
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
Message recived;
|
||||
std::string recivedMessage;
|
||||
int bytesRecived;
|
||||
|
||||
SOCKET lookingFor = copy_fd.fd_array[i];
|
||||
auto findedClient = std::find_if(connections.begin(), connections.end(), [lookingFor](clientInfo clientInfo) { return lookingFor == clientInfo.connection.GetSocket(); });
|
||||
|
||||
switch (findedClient->connection.ReciveAll(recivedMessage, bytesRecived))
|
||||
{
|
||||
case Result::Fail:
|
||||
case Result::ConnectionLost:
|
||||
{
|
||||
std::string nameLogOut = findedClient->name;
|
||||
FD_CLR(findedClient->connection.GetSocket(), &master_fd);
|
||||
findedClient->connection.Close();
|
||||
connections.erase(findedClient);
|
||||
|
||||
for (auto Client : connections)
|
||||
{
|
||||
if (!Client.name.empty())
|
||||
{
|
||||
// wysyla do pozostalych zalogowanych uzytkowniko kto sie wylogowal
|
||||
//if (Client.connection.GetSocket() != findedClient->connection.GetSocket())
|
||||
//{
|
||||
Message clientLogOut;
|
||||
|
||||
std::string msg = clientLogOut.PrepareCommand("", nameLogOut, Command::LogOut);
|
||||
if (Client.connection.SendAll(msg.c_str(), msg.size()) != Result::Success)
|
||||
{
|
||||
// cos poszlo nie tak
|
||||
}
|
||||
//}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case Result::Success:
|
||||
// TODO RecivesMessage BytesRecived
|
||||
findedClient->lastActiveTime = time(NULL);
|
||||
if (recived.Parse(recivedMessage.c_str(), bytesRecived) != Result::Success)
|
||||
{
|
||||
// wiadamosc niekompletna, bledna lub cos takiego
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
switch (recived.GetType())
|
||||
{
|
||||
case SocketLibrary::TypeOfMsg::Text:
|
||||
for (auto Client : connections)
|
||||
{
|
||||
if (Client.connection.GetSocket() != findedClient->connection.GetSocket())
|
||||
{
|
||||
if (Client.connection.SendAll(recivedMessage.c_str(), bytesRecived) != Result::Success)
|
||||
{
|
||||
// cos poszlo nie tak
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case SocketLibrary::TypeOfMsg::File:
|
||||
break;
|
||||
case SocketLibrary::TypeOfMsg::Command:
|
||||
{
|
||||
switch (recived.GetCommand())
|
||||
{
|
||||
case Command::Unknown:
|
||||
{
|
||||
std::string clientIP = findedClient->connection.GetEndpoint().GetIpString();
|
||||
std::string clientPort = std::to_string( findedClient->connection.GetEndpoint().GetPort() );
|
||||
std::string clientSocket = std::to_string( findedClient->connection.GetSocket() );
|
||||
|
||||
Log::PrintError("Nieprawidlowy lub brak komendy. [" + clientIP + ":" + clientPort + " SOCKET:" + clientSocket + "]", -1);
|
||||
return Result::Fail;
|
||||
break;
|
||||
}
|
||||
case Command::LogIn:
|
||||
{
|
||||
findedClient->name = recived.GetName();
|
||||
Log::Print(findedClient->name + " zalogowal sie z adresu" + findedClient->connection.GetEndpoint().GetIpString());
|
||||
for (auto Client : connections)
|
||||
{
|
||||
if (!Client.name.empty())
|
||||
{
|
||||
// wysyla do pozostalych zalogowanych uzytkownik, nowo zalogowanego uzytkownika
|
||||
// wysyla do nowo zalogowanego uzytkownika, pozostalych zalogowanych
|
||||
if (Client.connection.GetSocket() != findedClient->connection.GetSocket())
|
||||
{
|
||||
Message oldClients;
|
||||
std::string msgNewClientPort = std::to_string(findedClient->listening.GetPort());
|
||||
std::string msgToOtherClients = oldClients.PrepareCommand(msgNewClientPort,findedClient->name, Command::Adress);
|
||||
if (Client.connection.SendAll(msgToOtherClients.c_str(), msgToOtherClients.size()) != Result::Success)
|
||||
{
|
||||
// cos poszlo nie tak
|
||||
// pewnie zamknac polaczenie
|
||||
}
|
||||
|
||||
Message newClient;
|
||||
std::string msgOldClientPort = std::to_string(Client.listening.GetPort());
|
||||
std::string msgToNewClients = newClient.PrepareCommand(msgOldClientPort ,Client.name, Command::Adress);
|
||||
if (findedClient->connection.SendAll(msgToNewClients.c_str(), msgToNewClients.size()) != Result::Success)
|
||||
{
|
||||
// cos poszlo nie tak
|
||||
// pewnie zamknac polaczenie
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Command::LogOut:
|
||||
{
|
||||
std::string nameLogOut = recived.GetName();
|
||||
findedClient->name = "";
|
||||
Log::Print(nameLogOut + " wylogowal sie z adresu" + findedClient->connection.GetEndpoint().GetIpString());
|
||||
for (auto Client : connections)
|
||||
{
|
||||
if (!Client.name.empty())
|
||||
{
|
||||
// wysyla do pozostalych zalogowanych uzytkowniko kto sie wylogowal
|
||||
if (Client.connection.GetSocket() != findedClient->connection.GetSocket())
|
||||
{
|
||||
Message clientLogOut;
|
||||
|
||||
std::string msg = clientLogOut.PrepareCommand("", nameLogOut , Command::LogOut);
|
||||
if (Client.connection.SendAll(msg.c_str(), msg.size()) != Result::Success)
|
||||
{
|
||||
// cos poszlo nie tak
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Command::Adress:
|
||||
{
|
||||
int port = atoi(recived.GetMsg().c_str());
|
||||
Endpoint clientPortListenning = Endpoint(findedClient->connection.GetEndpoint().GetIpString().c_str(), (unsigned short)port);
|
||||
findedClient->listening = clientPortListenning;
|
||||
Log::Print("Odebralem port nasluchiwania klienta. [" + findedClient->listening.GetIpString() + ":" + std::to_string(findedClient->listening.GetPort()) + "]");
|
||||
|
||||
//std::string newClientPort = std::to_string(findedClient->listening.GetPort());
|
||||
//for (auto Client : connections)
|
||||
//{
|
||||
//
|
||||
// // wysyla adresy (porty) do uzytkownikow
|
||||
// if (Client.connection.GetSocket() != findedClient->connection.GetSocket())
|
||||
// {
|
||||
// Message oldClient;
|
||||
// std::string msgToOtherClients = oldClient.PrepareCommand(newClientPort, "server", Command::Adress);
|
||||
// if (Client.connection.SendAll(msgToOtherClients.c_str(), msgToOtherClients.size()) != Result::Success)
|
||||
// {
|
||||
// // cos poszlo nie tak
|
||||
// }
|
||||
|
||||
// Message newClient;
|
||||
// std::string oldClientPort = std::to_string(Client.listening.GetPort());
|
||||
// std::string msgToNewClient = newClient.PrepareCommand(oldClientPort, "server", Command::Adress);
|
||||
// if (findedClient->connection.SendAll(msgToNewClient.c_str(), msgToNewClient.size()) != Result::Success)
|
||||
// {
|
||||
// // cos poszlo nie tak
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//}
|
||||
break;
|
||||
}
|
||||
case Command::ConnCheck:
|
||||
{
|
||||
Log::Print("\"" + findedClient->name + "\" potwierdzil, ze jest wciaz aktywny.");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Result Server::CheckConnection()
|
||||
{
|
||||
//Sleep(1000);
|
||||
if (sendUDP)
|
||||
{
|
||||
std::string msg, msg2;
|
||||
std::ostringstream msgSize;
|
||||
msg = "server:" + listeningSocketTCP.GetEndpoint().GetIpString() + ":" + std::to_string(listeningSocketTCP.GetEndpoint().GetPort());
|
||||
|
||||
msgSize << std::setw(3) << std::setfill('0') << msg.size();
|
||||
msg = msgSize.str() + " " + msg;
|
||||
broadcastSenderUDP.SendUDP(msg, ownEndpoint);
|
||||
|
||||
}
|
||||
|
||||
/*for (auto client : connections)
|
||||
{
|
||||
Message chkMsg;
|
||||
std::string msg = chkMsg.PrepareCommand("", "server", Command::ConnCheck);
|
||||
if (client.lastActiveTime + 10 < time(NULL))
|
||||
{
|
||||
client.connection.SendAll(msg.c_str(), msg.size());
|
||||
|
||||
}
|
||||
}*/
|
||||
|
||||
return Result();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//for (auto sock = connections.begin(); sock != connections.end(); sock++)
|
||||
//{
|
||||
//
|
||||
// if (sock->GetSocket() == copy_fd.fd_array[i])
|
||||
// {
|
||||
// switch (sock->ReciveAll(recivedMessage, bytesRecived))
|
||||
// {
|
||||
// case Result::ConnectionLost:
|
||||
// FD_CLR(sock->GetSocket(), &master_fd);
|
||||
// connections.erase(sock);
|
||||
// sock->Close();
|
||||
// break;
|
||||
//
|
||||
// case Result::Success:
|
||||
//
|
||||
// case Result::Fail:
|
||||
//
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
6
SocketLibrary/Connection.cpp
Normal file
6
SocketLibrary/Connection.cpp
Normal file
@@ -0,0 +1,6 @@
|
||||
#include "Connection.h"
|
||||
|
||||
SocketLibrary::Connection::Connection(Socket socket, Endpoint endpoint)
|
||||
:socket(socket), endpoint(endpoint)
|
||||
{
|
||||
}
|
||||
15
SocketLibrary/Connection.h
Normal file
15
SocketLibrary/Connection.h
Normal file
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
#include <vector>
|
||||
#include "Socket.h"
|
||||
#include "Endpoint.h"
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
class Connection
|
||||
{
|
||||
Connection(Socket socket, Endpoint endpoint);
|
||||
|
||||
Endpoint endpoint;
|
||||
Socket socket;
|
||||
};
|
||||
}
|
||||
Binary file not shown.
@@ -1,2 +1,8 @@
|
||||
Source.cpp
|
||||
SocketLibrary.vcxproj -> C:\Users\bartool\MyData\MyCode\Cpp\VisualStudio_lap\LanChat\Debug\SocketLibrary.lib
|
||||
Connection.cpp
|
||||
Endpoint.cpp
|
||||
Log.cpp
|
||||
Message.cpp
|
||||
Network.cpp
|
||||
Socket.cpp
|
||||
C:\MyCode\Cpp\VisualStudio_lap\LanChat\SocketLibrary\Message.cpp(66,14): warning C4244: 'initializing': conversion from 'std::streamoff' to 'size_t', possible loss of data
|
||||
SocketLibrary.vcxproj -> C:\MyCode\Cpp\VisualStudio_lap\LanChat\Debug\SocketLibrary.lib
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,2 +1,2 @@
|
||||
#TargetFrameworkVersion=v4.0:PlatformToolSet=v142:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=10.0
|
||||
Debug|Win32|C:\Users\bartool\MyData\MyCode\Cpp\VisualStudio_lap\LanChat\|
|
||||
Debug|Win32|C:\MyCode\Cpp\VisualStudio_lap\LanChat\|
|
||||
|
||||
Binary file not shown.
101
SocketLibrary/Endpoint.cpp
Normal file
101
SocketLibrary/Endpoint.cpp
Normal file
@@ -0,0 +1,101 @@
|
||||
#include "Endpoint.h"
|
||||
//#include <WS2tcpip.h>
|
||||
#include "Log.h"
|
||||
#include <assert.h>
|
||||
|
||||
using namespace SocketLibrary;
|
||||
|
||||
Endpoint::Endpoint()
|
||||
{
|
||||
char ip[16];
|
||||
sockaddr_in newaddr;
|
||||
newaddr.sin_family = AF_INET;
|
||||
newaddr.sin_port = 0;
|
||||
newaddr.sin_addr.S_un.S_addr = INADDR_NONE;
|
||||
|
||||
// sockaddr_in* newaddr;
|
||||
_ipversion = IPVersion::IPv4;
|
||||
_port = ntohs(newaddr.sin_port);
|
||||
//_ip_string.resize(16);
|
||||
inet_ntop(AF_INET, &newaddr.sin_addr, /*&_ip_string[0]*/ ip, 16);
|
||||
//_ip_string.erase(_ip_string.find('\0'));
|
||||
_ip_string = ip;
|
||||
_hostname = _ip_string;
|
||||
|
||||
_socketaddr = newaddr;
|
||||
}
|
||||
|
||||
Endpoint::Endpoint(const char* ip, unsigned short port)
|
||||
{
|
||||
_port = port;
|
||||
|
||||
in_addr addr;
|
||||
int result = inet_pton(AF_INET, ip, &addr);
|
||||
|
||||
if (result == 1)
|
||||
{
|
||||
// if (addr.S_un.S_addr != INADDR_NONE)
|
||||
// {
|
||||
_ip_string = ip;
|
||||
_hostname = ip;
|
||||
_ipversion = IPVersion::IPv4;
|
||||
|
||||
_socketaddr.sin_family = AF_INET;
|
||||
_socketaddr.sin_port = htons(_port);
|
||||
memcpy(&_socketaddr.sin_addr, &addr, sizeof(in_addr));
|
||||
|
||||
return;
|
||||
// }
|
||||
}
|
||||
else
|
||||
{
|
||||
std::string invalidIP = ip;
|
||||
Log::PrintError("To nie jest prawidlowy adres IP. [" + invalidIP + "]", result);
|
||||
}
|
||||
}
|
||||
|
||||
Endpoint::Endpoint(sockaddr* addr)
|
||||
{
|
||||
assert(addr->sa_family == AF_INET);
|
||||
char ip[16];
|
||||
sockaddr_in* newaddr = (sockaddr_in*)addr;
|
||||
_ipversion = IPVersion::IPv4;
|
||||
_port = ntohs(newaddr->sin_port);
|
||||
//_ip_string.resize(16);
|
||||
inet_ntop(AF_INET, &newaddr->sin_addr, ip, 16);
|
||||
_ip_string = ip;
|
||||
_hostname = _ip_string;
|
||||
}
|
||||
|
||||
IPVersion Endpoint::GetIpVersion()
|
||||
{
|
||||
return _ipversion;
|
||||
}
|
||||
|
||||
std::string Endpoint::GetHostName()
|
||||
{
|
||||
return _hostname;
|
||||
}
|
||||
|
||||
std::string Endpoint::GetIpString()
|
||||
{
|
||||
return _ip_string;
|
||||
}
|
||||
|
||||
unsigned short Endpoint::GetPort()
|
||||
{
|
||||
return _port;
|
||||
}
|
||||
|
||||
sockaddr_in Endpoint::GetSocketaddrIP()
|
||||
{
|
||||
return _socketaddr;
|
||||
}
|
||||
|
||||
void SocketLibrary::Endpoint::Print()
|
||||
{
|
||||
Log::Print("Hostname: " + _hostname);
|
||||
Log::Print("IP: " + _ip_string);
|
||||
Log::Print("Port: " + std::to_string(_port));
|
||||
Log::Print("Family: " + std::to_string(_socketaddr.sin_family));
|
||||
}
|
||||
27
SocketLibrary/Endpoint.h
Normal file
27
SocketLibrary/Endpoint.h
Normal file
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
#include <sstream>
|
||||
#include <WS2tcpip.h>
|
||||
#include "ipVersion.h"
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
class Endpoint
|
||||
{
|
||||
public:
|
||||
Endpoint();
|
||||
Endpoint(const char* ip, unsigned short port);
|
||||
Endpoint(sockaddr* addr);
|
||||
IPVersion GetIpVersion();
|
||||
std::string GetHostName();
|
||||
std::string GetIpString();
|
||||
unsigned short GetPort();
|
||||
sockaddr_in GetSocketaddrIP();
|
||||
void Print();
|
||||
private:
|
||||
IPVersion _ipversion = IPVersion::Unknown;
|
||||
std::string _hostname = "";
|
||||
std::string _ip_string = "";
|
||||
unsigned short _port = 0;
|
||||
sockaddr_in _socketaddr = {};
|
||||
};
|
||||
}
|
||||
14
SocketLibrary/Log.cpp
Normal file
14
SocketLibrary/Log.cpp
Normal file
@@ -0,0 +1,14 @@
|
||||
#include <iostream>
|
||||
#include "Log.h"
|
||||
#include "Result.h"
|
||||
#include "ipVersion.h"
|
||||
|
||||
void SocketLibrary::Log::Print(std::string message)
|
||||
{
|
||||
std::cout << "[LOG] " << message << std::endl;
|
||||
}
|
||||
|
||||
void SocketLibrary::Log::PrintError(std::string message, int error)
|
||||
{
|
||||
std::cerr << "[ERROR] " << "[Error Code: " << error << "] "<< message << std::endl;
|
||||
}
|
||||
12
SocketLibrary/Log.h
Normal file
12
SocketLibrary/Log.h
Normal file
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
class Log
|
||||
{
|
||||
public:
|
||||
void static Print(std::string message);
|
||||
void static PrintError(std::string message, int error);
|
||||
};
|
||||
}
|
||||
208
SocketLibrary/Message.cpp
Normal file
208
SocketLibrary/Message.cpp
Normal file
@@ -0,0 +1,208 @@
|
||||
#include <sstream>
|
||||
|
||||
#include "Message.h"
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
Message::Message()
|
||||
{
|
||||
_name = "";
|
||||
_typeOfMsg = TypeOfMsg::Unknown;
|
||||
_lenght = 0;
|
||||
_totalLenght = 0;
|
||||
_message = {};
|
||||
_command = Command::Unknown;
|
||||
_filename = "";
|
||||
}
|
||||
|
||||
Result Message::Parse(const std::string& msg, int lenght)
|
||||
{
|
||||
std::string expression, left, right;
|
||||
std::stringstream msgStream;
|
||||
msgStream << msg;
|
||||
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
//std::getline(msgStream, expression);
|
||||
msgStream >> expression;
|
||||
|
||||
expression.replace(expression.find(':'), 1, " ");
|
||||
std::stringstream expStream(expression);
|
||||
|
||||
expStream >> left >> right;
|
||||
if (i == 0)
|
||||
{
|
||||
if (left == "who")
|
||||
_name = right;
|
||||
else return Result::Fail;
|
||||
|
||||
}
|
||||
else if (i == 1)
|
||||
{
|
||||
if (left == "what")
|
||||
{
|
||||
if (right == "text")
|
||||
_typeOfMsg = TypeOfMsg::Text;
|
||||
else if (right == "file")
|
||||
_typeOfMsg = TypeOfMsg::File;
|
||||
else if (right == "command")
|
||||
_typeOfMsg = TypeOfMsg::Command;
|
||||
else return Result::Fail;
|
||||
}
|
||||
else return Result::Fail;
|
||||
}
|
||||
else if (i == 2)
|
||||
{
|
||||
if (left == "sizetotal") _totalLenght = atoi(right.c_str());
|
||||
else return Result::Fail;
|
||||
}
|
||||
else if (i == 3)
|
||||
{
|
||||
if (left == "lenght") _lenght = atoi(right.c_str());
|
||||
else return Result::Fail;
|
||||
}
|
||||
}
|
||||
|
||||
size_t pos = msgStream.tellg();
|
||||
pos++;
|
||||
_message = msg.substr(pos);
|
||||
|
||||
if (_lenght != _message.size())
|
||||
{
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
|
||||
if (_typeOfMsg == TypeOfMsg::Command)
|
||||
{
|
||||
std::size_t pos = _message.find(':');
|
||||
std::string cmd = _message.substr(0, pos);
|
||||
if (cmd == "login")
|
||||
{
|
||||
_command = Command::LogIn;
|
||||
//_message = _message.substr(_message.find(':') + 1);
|
||||
}
|
||||
else if (cmd == "logout")
|
||||
{
|
||||
_command = Command::LogOut;
|
||||
//_message = _message.substr(_message.find(':') + 1);
|
||||
}
|
||||
else if (cmd == "adress")
|
||||
{
|
||||
_command = Command::Adress;
|
||||
_message = _message.substr(_message.find(':') + 1);
|
||||
}
|
||||
else if (cmd == "conn_check")
|
||||
{
|
||||
_command = Command::ConnCheck;
|
||||
}
|
||||
else if (cmd == "filename")
|
||||
{
|
||||
_command = Command::FileName;
|
||||
_filename = _message.substr(_message.find(':') + 1);
|
||||
}
|
||||
else return Result::Fail;
|
||||
}
|
||||
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
std::string Message::PrepareText(const std::string& msg, std::string name)
|
||||
{
|
||||
//"who:bart what:text sizetotal:10 lenght:10 tresc wiadomosci i tak dalej";
|
||||
int lenght = msg.size();
|
||||
std::string output;
|
||||
output = "who:" + name;
|
||||
output += " what:text";
|
||||
output += " sizetotal:" + std::to_string(lenght);
|
||||
output += " lenght:" + std::to_string(lenght);
|
||||
output += " " + msg;
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
std::string Message::PrepareFile(const std::string& msg, std::string name, int totalLenght)
|
||||
{
|
||||
//"who:bart what:file sizetotal:1000 lenght:10 ......plik.....binary......";
|
||||
int lenght = msg.size();
|
||||
std::string output;
|
||||
output = "who:" + name;
|
||||
output += " what:file";
|
||||
output += " sizetotal:" + std::to_string(totalLenght);
|
||||
output += " lenght:" + std::to_string(lenght);
|
||||
output += " " + msg;
|
||||
|
||||
return output;
|
||||
|
||||
}
|
||||
|
||||
std::string Message::PrepareCommand(const std::string& msg, std::string name, Command cmd)
|
||||
{
|
||||
std::string msgCmd;
|
||||
switch (cmd)
|
||||
{
|
||||
case SocketLibrary::Command::LogIn:
|
||||
msgCmd = " login:";// +name;
|
||||
break;
|
||||
case SocketLibrary::Command::LogOut:
|
||||
msgCmd = " logout:";// +name;
|
||||
break;
|
||||
case SocketLibrary::Command::Adress:
|
||||
msgCmd = " adress:" + msg;
|
||||
break;
|
||||
case SocketLibrary::Command::ConnCheck:
|
||||
msgCmd = " conn_check";
|
||||
break;
|
||||
case Command::FileName:
|
||||
msgCmd = " filename:" + msg;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
//msgCmd += msg;
|
||||
|
||||
int lenght = msgCmd.size()-1;
|
||||
std::string output;
|
||||
output = "who:" + name;
|
||||
output += " what:command";
|
||||
output += " sizetotal:" + std::to_string(lenght);
|
||||
output += " lenght:" + std::to_string(lenght);
|
||||
output += msgCmd;
|
||||
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
std::string Message::GetName()
|
||||
{
|
||||
return _name;
|
||||
}
|
||||
|
||||
TypeOfMsg Message::GetType()
|
||||
{
|
||||
return _typeOfMsg;
|
||||
}
|
||||
|
||||
int Message::GetLenght()
|
||||
{
|
||||
return _lenght;
|
||||
}
|
||||
|
||||
int Message::GetTotalLenght()
|
||||
{
|
||||
return _totalLenght;
|
||||
}
|
||||
|
||||
std::string Message::GetMsg()
|
||||
{
|
||||
return _message;
|
||||
}
|
||||
Command Message::GetCommand()
|
||||
{
|
||||
return _command;
|
||||
}
|
||||
std::string Message::GetFileName()
|
||||
{
|
||||
return _filename;
|
||||
}
|
||||
}
|
||||
51
SocketLibrary/Message.h
Normal file
51
SocketLibrary/Message.h
Normal file
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include "Result.h"
|
||||
namespace SocketLibrary
|
||||
{
|
||||
enum class TypeOfMsg
|
||||
{
|
||||
Unknown,
|
||||
Text,
|
||||
File,
|
||||
Command
|
||||
};
|
||||
|
||||
enum class Command
|
||||
{
|
||||
Unknown,
|
||||
LogIn,
|
||||
LogOut,
|
||||
Adress,
|
||||
ConnCheck,
|
||||
FileName
|
||||
};
|
||||
|
||||
class Message
|
||||
{
|
||||
public:
|
||||
Message();
|
||||
|
||||
|
||||
Result Parse(const std::string& msg, int size);
|
||||
std::string PrepareText(const std::string& msg, std::string name);
|
||||
std::string PrepareFile(const std::string& msg, std::string name, int totalLenght);
|
||||
std::string PrepareCommand(const std::string& msg, std::string name, Command cmd);
|
||||
std::string GetName();
|
||||
TypeOfMsg GetType();
|
||||
int GetLenght();
|
||||
int GetTotalLenght();
|
||||
std::string GetMsg();
|
||||
Command GetCommand();
|
||||
std::string GetFileName();
|
||||
private:
|
||||
std::string _name;
|
||||
TypeOfMsg _typeOfMsg;
|
||||
int _lenght;
|
||||
int _totalLenght;
|
||||
std::string _message;
|
||||
Command _command;
|
||||
std::string _filename;
|
||||
|
||||
};
|
||||
}
|
||||
37
SocketLibrary/Network.cpp
Normal file
37
SocketLibrary/Network.cpp
Normal file
@@ -0,0 +1,37 @@
|
||||
#include <WinSock2.h>
|
||||
|
||||
#include "Network.h"
|
||||
#include "Log.h"
|
||||
|
||||
bool SocketLibrary::Network::Initialize()
|
||||
{
|
||||
WSADATA wsadata;
|
||||
|
||||
int result = WSAStartup(MAKEWORD(2,2), &wsadata);
|
||||
if (result != 0)
|
||||
{
|
||||
Log::PrintError("Nie udalo sie uruchomic Winsock", result);
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log::Print("Winsock zostal uruchominy");
|
||||
}
|
||||
|
||||
if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 2)
|
||||
{
|
||||
Log::PrintError("Nie udalo sie uruchomic WinSock w najwyzszej wersji.", result);
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log::Print("Udalo sie uchomic WinSock w wersji 2,2.");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void SocketLibrary::Network::Shutdown()
|
||||
{
|
||||
WSACleanup();
|
||||
}
|
||||
14
SocketLibrary/Network.h
Normal file
14
SocketLibrary/Network.h
Normal file
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
|
||||
//#include <WinSock2.h>
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
class Network
|
||||
{
|
||||
public:
|
||||
static bool Initialize();
|
||||
static void Shutdown();
|
||||
};
|
||||
}
|
||||
33
SocketLibrary/Packet.h
Normal file
33
SocketLibrary/Packet.h
Normal file
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
|
||||
#include "Result.h"
|
||||
#include "Endpoint.h"
|
||||
#include "Socket.h"
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
enum class TypeOfMessage
|
||||
{
|
||||
Text,
|
||||
File,
|
||||
Command
|
||||
|
||||
};
|
||||
|
||||
class Packet
|
||||
{
|
||||
//Result ResolveServer(std::string input, Endpoint& server);
|
||||
|
||||
|
||||
//Result SendMsg(std::string message, Socket client);
|
||||
//Result SendFile(std::string file, Socket client);
|
||||
|
||||
std::string sender;
|
||||
TypeOfMessage typeOfMessage;
|
||||
int totalLenght;
|
||||
int msgLenght;
|
||||
std::string message;
|
||||
|
||||
};
|
||||
}
|
||||
12
SocketLibrary/Protocol.h
Normal file
12
SocketLibrary/Protocol.h
Normal file
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
enum class Protocol
|
||||
{
|
||||
Unknown,
|
||||
TCP,
|
||||
UDP_Sender,
|
||||
UDP_Reciver
|
||||
};
|
||||
}
|
||||
11
SocketLibrary/Result.h
Normal file
11
SocketLibrary/Result.h
Normal file
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
enum class Result
|
||||
{
|
||||
Success,
|
||||
Fail,
|
||||
ConnectionLost,
|
||||
};
|
||||
}
|
||||
441
SocketLibrary/Socket.cpp
Normal file
441
SocketLibrary/Socket.cpp
Normal file
@@ -0,0 +1,441 @@
|
||||
#include <iomanip>
|
||||
#include "Socket.h"
|
||||
#include "Log.h"
|
||||
#include <assert.h>
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
Socket::Socket(IPVersion ipversion, Protocol protocol, SOCKET socket)
|
||||
:_ipversion(ipversion), _socket(socket), _protocol(protocol)
|
||||
{
|
||||
assert(_ipversion == IPVersion::IPv4);
|
||||
|
||||
|
||||
}
|
||||
Socket::Socket(Protocol protocol)
|
||||
:_ipversion(IPVersion::IPv4), _protocol(protocol), _socket(INVALID_SOCKET)
|
||||
{
|
||||
}
|
||||
|
||||
Socket::Socket(SOCKET socket)
|
||||
:_ipversion(IPVersion::IPv4), _protocol(Protocol::TCP), _socket(socket)
|
||||
{
|
||||
}
|
||||
|
||||
Result Socket::Create()
|
||||
{
|
||||
assert(_ipversion == IPVersion::IPv4);
|
||||
|
||||
if (_socket != INVALID_SOCKET)
|
||||
{
|
||||
Log::PrintError("Gniazdo juz istnieje.", -1);
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log::Print("Gniazdo nie istnieje. Tworze gniazdo...");
|
||||
}
|
||||
|
||||
switch (_protocol)
|
||||
{
|
||||
case SocketLibrary::Protocol::Unknown:
|
||||
Log::PrintError("Nie mozna utworzyc gniazda o nieznamym typie.", -1);
|
||||
return Result::Fail;
|
||||
break;
|
||||
case SocketLibrary::Protocol::TCP:
|
||||
_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
break;
|
||||
case SocketLibrary::Protocol::UDP_Sender:
|
||||
case SocketLibrary::Protocol::UDP_Reciver:
|
||||
_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (_socket == INVALID_SOCKET)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Nie udalo sie utworzyc gniazda", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
std::string msg = "Gniazdo zostalo utworzone ";
|
||||
switch (_protocol)
|
||||
{
|
||||
case SocketLibrary::Protocol::TCP:
|
||||
msg += "[TCP] [SOCKET:";
|
||||
break;
|
||||
case SocketLibrary::Protocol::UDP_Sender:
|
||||
msg += "[UDP] [SOCKET:";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
Log::Print(msg + std::to_string(_socket) + "]");
|
||||
}
|
||||
|
||||
switch (_protocol)
|
||||
{
|
||||
case SocketLibrary::Protocol::TCP:
|
||||
if (SetSocketOption(SocketOption::TCP_NoDelay, TRUE) == Result::Success)
|
||||
{
|
||||
Log::Print("NoDelay zostalo wlaczone na gniezdzie TCP.");
|
||||
}
|
||||
break;
|
||||
case SocketLibrary::Protocol::UDP_Sender:
|
||||
if (SetSocketOption(SocketOption::UDP_Broadcast, TRUE) == Result::Success)
|
||||
{
|
||||
Log::Print("UDP_Broadcast zostalo wlaczone na gniezdzie UDP.");
|
||||
}
|
||||
break;
|
||||
case SocketLibrary::Protocol::UDP_Reciver:
|
||||
if (SetSocketOption(SocketOption::UDP_Reuseaddr, TRUE) == Result::Success)
|
||||
{
|
||||
Log::Print("UDP_Reuseaddr zostalo wlaczone na gniezdzie UDP.");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::Close()
|
||||
{
|
||||
if (_socket == INVALID_SOCKET)
|
||||
{
|
||||
Log::PrintError("Niemozna zamknac nieistniejacego gniazda.", -1);
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log::Print("Zamykam gniazdo [SOCKET:" + std::to_string(_socket) + "]");
|
||||
}
|
||||
|
||||
int result = closesocket(_socket);
|
||||
if (result != 0)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Nie udalo sie zamknac gniazda.", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log::Print("Gniazdo zostalo zamkniete.");
|
||||
}
|
||||
|
||||
_socket = INVALID_SOCKET;
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::AssignEndpoint(Endpoint endpoint)
|
||||
{
|
||||
_endpoint = endpoint;
|
||||
return Result();
|
||||
}
|
||||
|
||||
Result Socket::Bind(Endpoint endpoint)
|
||||
{
|
||||
sockaddr_in addr = endpoint.GetSocketaddrIP();
|
||||
int result = bind(_socket, (sockaddr*)(&addr), sizeof(sockaddr_in));
|
||||
if (result != 0)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Nie udalo sie powiazac gniazda z portem.", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log::Print("Udalo sie zwiazac gniazdo z wybranym portem. [PORT]:" + std::to_string(endpoint.GetPort())
|
||||
+ " [SOCKET]:" + std::to_string(_socket));
|
||||
}
|
||||
_endpoint = endpoint;
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::BindAndListen(Endpoint endpoint, int waitConnection)
|
||||
{
|
||||
if (Bind(endpoint) != Result::Success)
|
||||
{
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
int result = listen(_socket, waitConnection);
|
||||
if (result != 0)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Nie udalo sie ustawic gniazda w tryb nasluchu", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log::Print("Gniazdo jest od teraz w trybie nasluchu.");
|
||||
}
|
||||
// _endpoint = endpoint;
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::Accept(Socket& outSocket)
|
||||
{
|
||||
sockaddr_in addr = {};
|
||||
int len = sizeof(sockaddr_in);
|
||||
SOCKET acceptedConnection = accept(_socket, (sockaddr*)(&addr), &len);
|
||||
if (acceptedConnection == INVALID_SOCKET)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Wystapil problem przy akceptacji polaczenia.", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log::Print("Zaakceptowano nowe poleczenie [SOCKET:" + std::to_string(acceptedConnection) + "]");
|
||||
}
|
||||
|
||||
Endpoint newConnectionEndpoint((sockaddr*)&addr);
|
||||
newConnectionEndpoint.Print();
|
||||
|
||||
outSocket = Socket(IPVersion::IPv4, Protocol::TCP, acceptedConnection);
|
||||
outSocket._endpoint = newConnectionEndpoint;
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::Connect()
|
||||
{
|
||||
//if (_endpoint.GetSocketaddrIP() == ?)
|
||||
//{
|
||||
// Log::PrintError("Blad wewnetrny. Endpoint nie instnieje.",_socket);
|
||||
// return Result::Fail;
|
||||
//}
|
||||
|
||||
sockaddr_in addr = _endpoint.GetSocketaddrIP();
|
||||
int result = connect(_socket, (sockaddr*)(&addr), sizeof(sockaddr_in));
|
||||
if (result != 0)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Nie mozna nawiazac polaczenia z " + _endpoint.GetIpString(), error);
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log::Print("Nawiazano nowe polaczenie z " + _endpoint.GetIpString());
|
||||
}
|
||||
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::Connect(Endpoint endpoint)
|
||||
{
|
||||
sockaddr_in addr = endpoint.GetSocketaddrIP();
|
||||
int result = connect(_socket, (sockaddr*)(&addr), sizeof(sockaddr_in));
|
||||
if (result != 0)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Nie mozna nawiazac polaczenia z " + endpoint.GetIpString(), error);
|
||||
return Result::Fail;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log::Print("Nawiazano nowe polaczenie z " + endpoint.GetIpString());
|
||||
}
|
||||
_endpoint = endpoint;
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::SendUDP(std::string& listOfUsers, Endpoint server)
|
||||
{
|
||||
sockaddr_in reciverAddr = _endpoint.GetSocketaddrIP();
|
||||
int result = sendto(_socket, listOfUsers.c_str(), listOfUsers.size(), 0, (sockaddr*)&reciverAddr, sizeof(reciverAddr));
|
||||
if (result == SOCKET_ERROR)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Problem z wyslaniem danych przez UDP.", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
if (result != listOfUsers.size())
|
||||
{
|
||||
Log::PrintError("Nie udalo sie wyslac wszystkich danych przez UDP.", -1);
|
||||
return Result::Fail;
|
||||
}
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::ReciveUDP(std::string& output, int& numberOfBytes)
|
||||
{
|
||||
char reciveData[256] = {};
|
||||
sockaddr_in addr = {};
|
||||
int len = sizeof(addr);
|
||||
int bytesRecived = recvfrom(_socket, reciveData, 256, 0, (sockaddr*)&addr, &len);
|
||||
if (bytesRecived == SOCKET_ERROR)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Problem z odebraniem danych przez UDP.", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
std::stringstream msg (reciveData);
|
||||
msg >> len;
|
||||
msg.seekg(1, std::ios_base::cur);
|
||||
std::getline(msg, output);
|
||||
if (len != output.size())
|
||||
{
|
||||
Log::PrintError("Dlugosc odebranych danych sie nie zgadza [UDP]", -1);
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
numberOfBytes = len;
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::SendAll(const void* data, int numberOfBytes)
|
||||
{
|
||||
int totalBytesSent = 0;
|
||||
int numberBytesToSend = numberOfBytes;
|
||||
numberBytesToSend = htonl(numberBytesToSend);
|
||||
Result result = Send(&numberBytesToSend, sizeof(int), totalBytesSent);
|
||||
if (result != Result::Success)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
if (totalBytesSent != sizeof(int))
|
||||
{
|
||||
Log::PrintError("Nie mozna wyslac dlugosci pakietu.", -1);
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
totalBytesSent = 0;
|
||||
|
||||
while (totalBytesSent < numberOfBytes)
|
||||
{
|
||||
int bytesLeft = numberOfBytes - totalBytesSent;
|
||||
int bytesSent = 0;
|
||||
char* bufferOffset = (char*)data + totalBytesSent;
|
||||
result = Send(bufferOffset, bytesLeft, bytesSent);
|
||||
if (result == Result::Fail)
|
||||
{
|
||||
Log::PrintError("Wyslalem " + std::to_string(totalBytesSent) + " z " + std::to_string(numberOfBytes) + " bajtow.", -1);
|
||||
return Result::Fail;
|
||||
}
|
||||
totalBytesSent += bytesSent;
|
||||
}
|
||||
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::ReciveAll(std::string& output, int& numberOfBytes)
|
||||
{
|
||||
int totalBytesRecive = 0;
|
||||
int numberBytesToRecive = 0;
|
||||
Result result = Recive(&numberBytesToRecive, sizeof(int), totalBytesRecive);
|
||||
if (result != Result::Success)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
if (totalBytesRecive != sizeof(int))
|
||||
{
|
||||
Log::PrintError("Nie mozna odebrac dlugosci pakietu", -1);
|
||||
return Result::Fail;
|
||||
|
||||
}
|
||||
|
||||
totalBytesRecive = 0;
|
||||
numberBytesToRecive = ntohl(numberBytesToRecive);
|
||||
output.resize(numberBytesToRecive );//+1
|
||||
|
||||
while (totalBytesRecive < numberBytesToRecive)
|
||||
{
|
||||
int bytesLeft = numberBytesToRecive - totalBytesRecive;
|
||||
int bytesRecive = 0;
|
||||
char* bufferOffset = &output[0] + totalBytesRecive;
|
||||
Result result = Recive(bufferOffset, bytesLeft, bytesRecive);
|
||||
if (result == Result::Fail)
|
||||
{
|
||||
Log::PrintError("Odebralem " + std::to_string(totalBytesRecive) + " z " + std::to_string(numberBytesToRecive) + " bajtow.", -1);
|
||||
return Result::Fail;
|
||||
}
|
||||
totalBytesRecive += bytesRecive;
|
||||
}
|
||||
numberOfBytes = totalBytesRecive;
|
||||
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
SOCKET Socket::GetSocket()
|
||||
{
|
||||
return _socket;
|
||||
}
|
||||
|
||||
IPVersion Socket::GetIpVersion()
|
||||
{
|
||||
return _ipversion;
|
||||
}
|
||||
|
||||
Endpoint Socket::GetEndpoint()
|
||||
{
|
||||
return _endpoint;
|
||||
}
|
||||
|
||||
Result Socket::Send(const void* data, int size, int& bytesSent)
|
||||
{
|
||||
bytesSent = send(_socket, (const char*)data, size, NULL);
|
||||
|
||||
if (bytesSent == SOCKET_ERROR)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Wystapil problem podczas wysylania dancyh.", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::Recive(void* buffor, int size, int& bytesRecived)
|
||||
{
|
||||
bytesRecived = recv(_socket, (char*)buffor, size, NULL);
|
||||
if (bytesRecived == 0)
|
||||
{
|
||||
Log::PrintError("Polaczenie zostalo zamkniete.", -1);
|
||||
// TODO - zamknac gniazdo
|
||||
return Result::ConnectionLost;
|
||||
}
|
||||
if (bytesRecived == SOCKET_ERROR)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Wystapil problem podczas odbierania dancyh.", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
return Result::Success;
|
||||
}
|
||||
|
||||
Result Socket::SetSocketOption(SocketOption option, BOOL value)
|
||||
{
|
||||
int result = 0;
|
||||
switch (option)
|
||||
{
|
||||
case SocketOption::TCP_NoDelay:
|
||||
result = setsockopt(_socket, IPPROTO_TCP, TCP_NODELAY, (const char*)&value, sizeof(value));
|
||||
break;
|
||||
case SocketOption::UDP_Broadcast:
|
||||
result = setsockopt(_socket, SOL_SOCKET, SO_BROADCAST, (const char*)&value, sizeof(value));
|
||||
break;
|
||||
case SocketOption::UDP_Reuseaddr:
|
||||
result = setsockopt(_socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&value, sizeof(value));
|
||||
break;
|
||||
default:
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
if (result != 0)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
Log::PrintError("Nie mozna ustawic opcji dla gniazda.", error);
|
||||
return Result::Fail;
|
||||
}
|
||||
|
||||
return Result::Success;
|
||||
}
|
||||
}
|
||||
43
SocketLibrary/Socket.h
Normal file
43
SocketLibrary/Socket.h
Normal file
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
#include <WinSock2.h>
|
||||
#include <vector>
|
||||
#include "ipVersion.h"
|
||||
#include "Protocol.h"
|
||||
#include "Result.h"
|
||||
#include "SocketOption.h"
|
||||
#include "Endpoint.h"
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
class Socket
|
||||
{
|
||||
public:
|
||||
Socket(IPVersion ipversion = IPVersion::IPv4, Protocol protocol = Protocol::TCP, SOCKET socket = INVALID_SOCKET); //(..., SocketHandle handle)
|
||||
Socket(Protocol protocol);
|
||||
Socket(SOCKET socket);
|
||||
Result Create();
|
||||
Result Close();
|
||||
Result AssignEndpoint(Endpoint endpoint);
|
||||
Result Bind(Endpoint endpoint);
|
||||
Result BindAndListen(Endpoint endpoint, int waitConnection = 5);
|
||||
Result Accept(Socket& outSocket);
|
||||
Result Connect();
|
||||
Result Connect(Endpoint endpoint);
|
||||
Result SendUDP(std::string& listOfUsers, Endpoint server);
|
||||
Result ReciveUDP(std::string& output, int& numberOfBytes);
|
||||
Result SendAll(const void * data, int numberOfBytes);
|
||||
Result ReciveAll(std::string& output, int& numberOfBytes);
|
||||
SOCKET GetSocket(); //SocketHandle GetHandle()
|
||||
IPVersion GetIpVersion();
|
||||
Endpoint GetEndpoint();
|
||||
private:
|
||||
Result Send(const void * data, int size, int& bytesSent);
|
||||
Result Recive(void * buffor, int size, int & bytesRecived);
|
||||
Result SetSocketOption(SocketOption option, BOOL value);
|
||||
IPVersion _ipversion = IPVersion::IPv4;
|
||||
Protocol _protocol = Protocol::TCP;
|
||||
SOCKET _socket = INVALID_SOCKET;
|
||||
Endpoint _endpoint = {};
|
||||
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
#include "Network.h"
|
||||
#include "Socket.h"
|
||||
#include "Connection.h"
|
||||
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
int ReturnFive();
|
||||
}
|
||||
#include "Log.h"
|
||||
#include "Message.h"
|
||||
@@ -142,10 +142,27 @@
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="Connection.h" />
|
||||
<ClInclude Include="Endpoint.h" />
|
||||
<ClInclude Include="ipVersion.h" />
|
||||
<ClInclude Include="Log.h" />
|
||||
<ClInclude Include="Message.h" />
|
||||
<ClInclude Include="Network.h" />
|
||||
<ClInclude Include="Packet.h" />
|
||||
<ClInclude Include="Protocol.h" />
|
||||
<ClInclude Include="Result.h" />
|
||||
<ClInclude Include="Socket.h" />
|
||||
<ClInclude Include="SocketLibrary.h" />
|
||||
<ClInclude Include="SocketOption.h" />
|
||||
<ClInclude Include="TypeOfConnection.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="Source.cpp" />
|
||||
<ClCompile Include="Connection.cpp" />
|
||||
<ClCompile Include="Endpoint.cpp" />
|
||||
<ClCompile Include="Log.cpp" />
|
||||
<ClCompile Include="Message.cpp" />
|
||||
<ClCompile Include="Network.cpp" />
|
||||
<ClCompile Include="Socket.cpp" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
|
||||
@@ -18,9 +18,60 @@
|
||||
<ClInclude Include="SocketLibrary.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Network.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Log.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Result.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="ipVersion.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Socket.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="SocketOption.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Endpoint.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Protocol.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="TypeOfConnection.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Connection.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Packet.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Message.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="Source.cpp">
|
||||
<ClCompile Include="Network.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="Log.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="Socket.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="Endpoint.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="Connection.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="Message.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
|
||||
11
SocketLibrary/SocketOption.h
Normal file
11
SocketLibrary/SocketOption.h
Normal file
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
enum class SocketOption
|
||||
{
|
||||
TCP_NoDelay,
|
||||
UDP_Broadcast,
|
||||
UDP_Reuseaddr
|
||||
};
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
#include "SocketLibrary.h"
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
int ReturnFive()
|
||||
{
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
13
SocketLibrary/TypeOfConnection.h
Normal file
13
SocketLibrary/TypeOfConnection.h
Normal file
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
enum class TypeOfConnection
|
||||
{
|
||||
None,
|
||||
Listener,
|
||||
Reciever,
|
||||
Sender,
|
||||
TwoWay,
|
||||
};
|
||||
}
|
||||
12
SocketLibrary/ipVersion.h
Normal file
12
SocketLibrary/ipVersion.h
Normal file
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
namespace SocketLibrary
|
||||
{
|
||||
|
||||
enum class IPVersion
|
||||
{
|
||||
Unknown,
|
||||
IPv4,
|
||||
IPv6
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user