11#include < tcpsocket.h>
2- #include < iostream>
3-
42TCPSocket::TCPSocket (std::function<void (int , std::string)> onError, int socketId) : BaseSocket(onError, TCP, socketId)
53{
6-
74}
85
96int TCPSocket::Send (std::string message)
107{
118 return this ->Send (message.c_str (), message.length ());
129}
1310
14- int TCPSocket::Send (const char * bytes, size_t byteslength)
11+ int TCPSocket::Send (const char * bytes, size_t byteslength)
1512{
1613 if (this ->isClosed )
17- {
1814 return -1 ;
19- }
2015
2116 int sent = 0 ;
2217 if ((sent = send (this ->sock , bytes, byteslength, 0 )) < 0 )
@@ -26,7 +21,7 @@ int TCPSocket::Send(const char* bytes, size_t byteslength)
2621 return sent;
2722}
2823
29- void TCPSocket::Connect ( std::string ipv4, uint16_t port, std::function<void ()> onConnected, std::function<void(int , std::string)> onError)
24+ void TCPSocket::Connect (std::string ipv4, uint16_t port, std::function<void ()> onConnected, std::function<void(int , std::string)> onError)
3025{
3126 if (inet_pton (AF_INET, ipv4.c_str (), &this ->address .sin_addr ) <= 0 )
3227 {
@@ -38,8 +33,7 @@ void TCPSocket::Connect( std::string ipv4, uint16_t port, std::function<void()>
3833 this ->Connect ((uint32_t )this ->address .sin_addr .s_addr , port, onConnected, onError);
3934}
4035
41-
42- void TCPSocket::Connect ( uint32_t IPv4, uint16_t port, std::function<void ()> onConnected, std::function<void(int , std::string)> onError)
36+ void TCPSocket::Connect (uint32_t IPv4, uint16_t port, std::function<void ()> onConnected, std::function<void(int , std::string)> onError)
4337{
4438 this ->address .sin_family = AF_INET;
4539 this ->address .sin_port = htons (port);
@@ -75,25 +69,12 @@ void TCPSocket::Receive(TCPSocket *socket)
7569{
7670 char tempBuffer[BUFFER_SIZE];
7771 int messageLength;
78- while ((messageLength = recv (socket->sock , tempBuffer, BUFFER_SIZE, 0 )) >= 0 )
79- {
80- if (messageLength > 0 )
81- {
82- if (socket->onMessageReceived )
83- socket->onMessageReceived (std::string (tempBuffer).substr (0 , messageLength));
84- }
85- else
86- {
87- socket->Close ();
88- if (socket->onSocketClosed )
89- socket->onSocketClosed ();
90- }
91- }
9272
93- // If socket crashed:
94- if (!socket->isClosed )
73+ while ((messageLength = recv (socket->sock , tempBuffer, BUFFER_SIZE, 0 )) > 0 )
9574 {
96- std::cerr << " Socket closed with error." << std::endl;
97- perror (" recv" );
75+ socket->onMessageReceived (std::string (tempBuffer).substr (0 , messageLength));
9876 }
77+
78+ socket->Close ();
79+ socket->onSocketClosed ();
9980}
0 commit comments