forked from compilelife/feiq
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcpsocket.cpp
More file actions
113 lines (97 loc) · 2.1 KB
/
tcpsocket.cpp
File metadata and controls
113 lines (97 loc) · 2.1 KB
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
110
111
112
113
#include "tcpsocket.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <sys/time.h>
#include <errno.h>
#include <unistd.h>
TcpSocket::TcpSocket()
{
}
TcpSocket::TcpSocket(int socket)
{
mSocket = socket;
if (mSocket != -1)
{
sockaddr_in addr;
socklen_t len = sizeof(addr);
auto ret = getpeername(mSocket, (sockaddr*)&addr, &len);
if (ret == 0)
{
mPeerIp = inet_ntoa(addr.sin_addr);
}
}
}
TcpSocket::~TcpSocket()
{
disconnect();
}
bool TcpSocket::connect(const string &ip, int port)
{
if (mSocket != -1)
return true;
mSocket = socket(AF_INET, SOCK_STREAM, 0);
if (mSocket == -1)
{
perror("faield to create socket");
return false;
}
sockaddr_in addr;
addr.sin_addr.s_addr = inet_addr(ip.c_str());
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
int ret = ::connect(mSocket, (sockaddr*)&addr, sizeof(addr));
if (ret == -1)
{
perror("failed to connect");
close(mSocket);
return false;
}
mPeerIp = ip;
return true;
}
void TcpSocket::disconnect()
{
if (mSocket != -1)
{
close(mSocket);
mPeerIp="";
}
}
int TcpSocket::send(const void *data, int size)
{
int sent = 0;
auto pdata = static_cast<const char*>(data);
while (sent < size)
{
int ret = ::send(mSocket, pdata+sent, size-sent, 0);
if (ret == -1 )
{
if (errno != EAGAIN)
{
perror("tcp send failed");
return -1;
}
continue;
}
sent+=ret;
}
return sent;
}
int TcpSocket::recv(void *data, int size, int msTimeout)
{
timeval tv = {msTimeout/1000, (msTimeout%1000)*1000};
setsockopt(mSocket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
int ret = ::recv(mSocket, data, size, 0);
if (ret == -1)
{
if (errno == ETIMEDOUT || errno == EAGAIN)
return -1;
else
{
perror("recv failed");
return -2;
}
}
return ret;
}