-
Notifications
You must be signed in to change notification settings - Fork 6
/
tcp_sink.cpp
110 lines (89 loc) · 2.57 KB
/
tcp_sink.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//
// Author: Alexander Sholohov <[email protected]>
//
// License: MIT
//
#include <stdio.h>
#include <unistd.h>
#include <netdb.h>
#include <errno.h>
#include "tcp_sink.h"
//---------------------------------------------------------------------------------------
CTcpSink::CTcpSink(int socket, size_t bufferSize, bool backReadEnabled)
: m_socket(socket)
, m_buffer(bufferSize)
, m_needDelete(false)
, m_backReadEnabled(backReadEnabled)
, m_errorPrinted(false)
{
}
//---------------------------------------------------------------------------------------
void CTcpSink::close()
{
if( m_socket )
{
::close(m_socket);
m_socket = 0;
}
}
//---------------------------------------------------------------------------------------------------
void CTcpSink::markForDelete()
{
m_needDelete = true;
}
//---------------------------------------------------------------------------------------------------
void CTcpSink::putData(const char* buf, size_t len)
{
m_buffer.put(buf, len);
doWrite();
}
//---------------------------------------------------------------------------------------------------
void CTcpSink::putData(std::vector<char> data)
{
putData( &data[0], data.size() );
}
//---------------------------------------------------------------------------------------------------
void CTcpSink::doWrite()
{
if( m_needDelete )
{
//printf("in doWrite need Del signalled (%d)\n", m_socket);
return;
}
size_t len = m_buffer.bytesAvailable();
if( len == 0 )
return;
std::vector<char> tmpBuf(len);
m_buffer.peek(tmpBuf, len);
int written = ::send(m_socket, &tmpBuf[0], len, MSG_NOSIGNAL);
if( written < 0 )
{
bool overload = ( errno == EWOULDBLOCK || errno == EAGAIN ); // On Linux this is the same codes
if( !m_errorPrinted )
{
if( overload )
{
// Not an error. The socket is still busy sending the previous data.
printf("o");fflush(stdout);
}
else
{
printf("Sink socket (%d) got error: %d ", m_socket, errno);fflush(stdout);
}
m_errorPrinted = true;
}
if( !overload )
{
// some error happen
m_needDelete = true;
}
return;
}
m_buffer.consume( written );
m_errorPrinted = false;
}
//---------------------------------------------------------------------------------------------------
bool CTcpSink::isWritePending() const
{
return m_buffer.bytesAvailable() > 0;
}