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

@@ -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,
};
}