final app

This commit is contained in:
2020-01-11 07:05:54 +01:00
parent dcfb945c0b
commit 31fe531703
68 changed files with 62242 additions and 129 deletions

View File

@@ -155,6 +155,10 @@
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="client.cpp" />
<ClCompile Include="main.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="client.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">

View File

@@ -18,5 +18,13 @@
<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>

View File

@@ -1 +1,13 @@
 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

View File

@@ -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.

View File

@@ -1,45 +1,540 @@
//Client
#include <SocketLibrary/SocketLibrary.h>
//#include <string>
//client
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <ctime>
#include <fstream>
#include <iomanip>
#include "client.h"
using namespace SocketLibrary;
int main()
Result Client::Initialize(Endpoint ip)
{
if (Network::Initialize() == true)
connections.clear();
FD_ZERO(&master_fd);
if (Network::Initialize())
{
Log::Print("[CLIENT] Winsok zostal zainicjolizowany. Mozemy dzialac.");
Socket socket;
if (socket.Create() == Result::Success)
// Winsock dziala
std::cout << "[CLIENT] Winsock zostal poprawnie zainicjalizowany." << std::endl;
broadcastReciverUDP = Socket(Protocol::UDP_Reciver);
if (broadcastReciverUDP.Create() == Result::Success)
{
Log::Print("[CLIENT] Utworzylem socket.");
if (socket.Connect(Endpoint("127.0.0.1", 54000)) == 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)
{
Log::Print("[CLIENT] Polaczylem sie serverem.");
std::string outString = "Wysylam z klienta.";
char buffer[256];
strcpy_s(buffer, "witam z klienta!\0");
while (true)
// 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, &copy_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)
{
socket.SendAll(outString.data(), outString.size());
//socket.SendAll(buffer, 256);
std::cout << "wyslalem 256 bajtow" << std::endl;
Sleep(1000);
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;
socket.Close();
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;
}
}
}
}
Network::Shutdown();
system("pause");
return 0;
}
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

42
Client/client.h Normal file
View 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
View 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

File diff suppressed because one or more lines are too long

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

File diff suppressed because one or more lines are too long

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.

Binary file not shown.

View File

@@ -1,12 +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\server.obj
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\debug\server.ilk
c:\users\bartool\mydata\mycode\cpp\visualstudio_lap\lanchat\debug\server.exe
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.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

View File

@@ -1 +1,4 @@
 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

View File

@@ -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.

30
Server/Server.h Normal file
View 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;
};

View File

@@ -154,8 +154,12 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.cpp" />
<ClCompile Include="server.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Server.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>

View File

@@ -18,5 +18,13 @@
<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>

89
Server/main.cpp Normal file
View 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;
//}

View File

@@ -1,58 +1,382 @@
//Server
#include <SocketLibrary/SocketLibrary.h>
//#include <SocketLibrary/SocketLibrary.h>
#include <iostream>
using namespace SocketLibrary;
#include <algorithm>
#include <iomanip>
int main()
{
if (Network::Initialize() == true)
{
Log::Print("[SERVER] Winsok zostal zainicjolizowany. Mozemy dzialac.");
#include "Server.h"
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)
{
Log::Print("[SERVER] sukces");
Socket newConnection;
if (socketTCP.Accpet(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;
}
//(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
//(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, &copy_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;
// }
// }
//}

View File

@@ -0,0 +1,6 @@
#include "Connection.h"
SocketLibrary::Connection::Connection(Socket socket, Endpoint endpoint)
:socket(socket), endpoint(endpoint)
{
}

View 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;
};
}

View File

@@ -1,3 +1,8 @@
 Socket.cpp
C:\Users\bartool\MyData\MyCode\Cpp\VisualStudio_lap\LanChat\SocketLibrary\Socket.cpp(239,27): warning C4018: '<': signed/unsigned mismatch
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

View File

@@ -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\|

View File

@@ -5,17 +5,37 @@
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)
{
this->_port = 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)
{
// if (addr.S_un.S_addr != INADDR_NONE)
// {
_ip_string = ip;
_hostname = ip;
_ipversion = IPVersion::IPv4;
@@ -25,7 +45,7 @@ Endpoint::Endpoint(const char* ip, unsigned short port)
memcpy(&_socketaddr.sin_addr, &addr, sizeof(in_addr));
return;
}
// }
}
else
{
@@ -37,11 +57,13 @@ Endpoint::Endpoint(const char* ip, unsigned short port)
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_string[0], 16);
//_ip_string.resize(16);
inet_ntop(AF_INET, &newaddr->sin_addr, ip, 16);
_ip_string = ip;
_hostname = _ip_string;
}

View File

@@ -1,5 +1,5 @@
#pragma once
#include <string>
#include <sstream>
#include <WS2tcpip.h>
#include "ipVersion.h"
@@ -8,6 +8,7 @@ namespace SocketLibrary
class Endpoint
{
public:
Endpoint();
Endpoint(const char* ip, unsigned short port);
Endpoint(sockaddr* addr);
IPVersion GetIpVersion();

208
SocketLibrary/Message.cpp Normal file
View 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
View 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;
};
}

33
SocketLibrary/Packet.h Normal file
View 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;
};
}

View File

@@ -2,11 +2,11 @@
namespace SocketLibrary
{
enum class Protocol
{
Unknown,
TCP,
UDP
UDP_Sender,
UDP_Reciver
};
}

View File

@@ -5,6 +5,7 @@ namespace SocketLibrary
enum class Result
{
Success,
Fail
Fail,
ConnectionLost,
};
}

View File

@@ -1,3 +1,4 @@
#include <iomanip>
#include "Socket.h"
#include "Log.h"
#include <assert.h>
@@ -14,7 +15,11 @@ namespace SocketLibrary
Socket::Socket(Protocol protocol)
:_ipversion(IPVersion::IPv4), _protocol(protocol), _socket(INVALID_SOCKET)
{
assert(_ipversion == IPVersion::IPv4);
}
Socket::Socket(SOCKET socket)
:_ipversion(IPVersion::IPv4), _protocol(Protocol::TCP), _socket(socket)
{
}
Result Socket::Create()
@@ -40,7 +45,8 @@ namespace SocketLibrary
case SocketLibrary::Protocol::TCP:
_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
break;
case SocketLibrary::Protocol::UDP:
case SocketLibrary::Protocol::UDP_Sender:
case SocketLibrary::Protocol::UDP_Reciver:
_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
break;
default:
@@ -55,7 +61,19 @@ namespace SocketLibrary
}
else
{
Log::Print("Gniazdo zostalo utworzone. [SOCKET:" + std::to_string(_socket) + "]");
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)
@@ -66,12 +84,18 @@ namespace SocketLibrary
Log::Print("NoDelay zostalo wlaczone na gniezdzie TCP.");
}
break;
case SocketLibrary::Protocol::UDP:
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;
}
@@ -108,6 +132,12 @@ namespace SocketLibrary
return Result::Success;
}
Result Socket::AssignEndpoint(Endpoint endpoint)
{
_endpoint = endpoint;
return Result();
}
Result Socket::Bind(Endpoint endpoint)
{
sockaddr_in addr = endpoint.GetSocketaddrIP();
@@ -123,7 +153,7 @@ namespace SocketLibrary
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;
}
@@ -145,11 +175,11 @@ namespace SocketLibrary
{
Log::Print("Gniazdo jest od teraz w trybie nasluchu.");
}
// _endpoint = endpoint;
return Result::Success;
}
Result Socket::Accpet(Socket& outSocket)
Result Socket::Accept(Socket& outSocket)
{
sockaddr_in addr = {};
int len = sizeof(sockaddr_in);
@@ -169,6 +199,31 @@ namespace SocketLibrary
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;
}
@@ -186,19 +241,68 @@ namespace SocketLibrary
{
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;
uint32_t numberBytesToSend = numberOfBytes;
int numberBytesToSend = numberOfBytes;
numberBytesToSend = htonl(numberBytesToSend);
Result result = Send(&numberBytesToSend, sizeof(uint32_t), totalBytesSent);
if (totalBytesSent != sizeof(uint32_t))
Result result = Send(&numberBytesToSend, sizeof(int), totalBytesSent);
if (result != Result::Success)
{
Log::PrintError("Nie mozna wyslac dlugosci strumienia danych.", -1);
return result;
}
if (totalBytesSent != sizeof(int))
{
Log::PrintError("Nie mozna wyslac dlugosci pakietu.", -1);
return Result::Fail;
}
@@ -224,17 +328,22 @@ namespace SocketLibrary
Result Socket::ReciveAll(std::string& output, int& numberOfBytes)
{
int totalBytesRecive = 0;
uint32_t numberBytesToRecive = 0;
Result result = Recive(&numberBytesToRecive, sizeof(uint32_t), totalBytesRecive);
if (totalBytesRecive != sizeof(uint32_t))
int numberBytesToRecive = 0;
Result result = Recive(&numberBytesToRecive, sizeof(int), totalBytesRecive);
if (result != Result::Success)
{
Log::PrintError("Nie mozna odebrac dlugosci strumienia dancyh.", -1);
Result::Fail;
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);
output.resize(numberBytesToRecive );//+1
while (totalBytesRecive < numberBytesToRecive)
{
@@ -244,7 +353,7 @@ namespace SocketLibrary
Result result = Recive(bufferOffset, bytesLeft, bytesRecive);
if (result == Result::Fail)
{
Log::PrintError("Odebralem " + std::to_string(totalBytesRecive) + " z " + std::to_string(numberOfBytes) + " bajtow.", -1);
Log::PrintError("Odebralem " + std::to_string(totalBytesRecive) + " z " + std::to_string(numberBytesToRecive) + " bajtow.", -1);
return Result::Fail;
}
totalBytesRecive += bytesRecive;
@@ -264,6 +373,11 @@ namespace SocketLibrary
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);
@@ -285,7 +399,7 @@ namespace SocketLibrary
{
Log::PrintError("Polaczenie zostalo zamkniete.", -1);
// TODO - zamknac gniazdo
return Result::Fail;
return Result::ConnectionLost;
}
if (bytesRecived == SOCKET_ERROR)
{
@@ -308,6 +422,9 @@ namespace SocketLibrary
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;
}
@@ -321,4 +438,4 @@ namespace SocketLibrary
return Result::Success;
}
}
}

View File

@@ -1,6 +1,6 @@
#pragma once
#include <WinSock2.h>
#include <vector>
#include "ipVersion.h"
#include "Protocol.h"
#include "Result.h"
@@ -14,16 +14,22 @@ namespace SocketLibrary
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 Accpet(Socket& outSocket);
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);
@@ -31,6 +37,7 @@ namespace SocketLibrary
IPVersion _ipversion = IPVersion::IPv4;
Protocol _protocol = Protocol::TCP;
SOCKET _socket = INVALID_SOCKET;
Endpoint _endpoint = {};
};
}

View File

@@ -1,5 +1,7 @@
#pragma once
#include "Network.h"
#include "Socket.h"
#include "Connection.h"
#include "Log.h"
#include "Log.h"
#include "Message.h"

View File

@@ -142,19 +142,25 @@
</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="Connection.cpp" />
<ClCompile Include="Endpoint.cpp" />
<ClCompile Include="Log.cpp" />
<ClCompile Include="Message.cpp" />
<ClCompile Include="Network.cpp" />
<ClCompile Include="Socket.cpp" />
</ItemGroup>

View File

@@ -42,6 +42,18 @@
<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="Network.cpp">
@@ -56,5 +68,11 @@
<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>
</Project>

View File

@@ -6,5 +6,6 @@ namespace SocketLibrary
{
TCP_NoDelay,
UDP_Broadcast,
UDP_Reuseaddr
};
}

View File

@@ -0,0 +1,13 @@
#pragma once
namespace SocketLibrary
{
enum class TypeOfConnection
{
None,
Listener,
Reciever,
Sender,
TwoWay,
};
}