-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathTcpSocket.hpp
79 lines (60 loc) · 2.03 KB
/
TcpSocket.hpp
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
/*
* Cross-platform compatibility superclass for sockets
*
* Copyright (C) 2019 Simon D. Levy
*
* MIT License
*/
#pragma once
#include "SocketCompat.hpp"
class TcpSocket : public Socket {
protected:
char _host[200];
char _port[10];
SOCKET _conn;
struct addrinfo * _addressInfo;
bool _connected;
TcpSocket(const char * host, const short port)
{
sprintf_s(_host, "%s", host);
sprintf_s(_port, "%d", port);
// No connection yet
_sock = INVALID_SOCKET;
_connected = false;
*_message = 0;
// Initialize Winsock, returning on failure
if (!initWinsock()) return;
// Set up client address info
struct addrinfo hints = {0};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
// Resolve the server address and port, returning on failure
_addressInfo = NULL;
int iResult = getaddrinfo(_host, _port, &hints, &_addressInfo);
if ( iResult != 0 ) {
sprintf_s(_message, "getaddrinfo() failed with error: %d", iResult);
cleanup();
return;
}
// Create a SOCKET for connecting to server, returning on failure
_sock = socket(_addressInfo->ai_family, _addressInfo->ai_socktype, _addressInfo->ai_protocol);
if (_sock == INVALID_SOCKET) {
sprintf_s(_message, "socket() failed");
cleanup();
return;
}
}
public:
bool sendData(void *buf, size_t len)
{
return (size_t)send(_conn, (const char *)buf, len, 0) == len;
}
bool receiveData(void *buf, size_t len)
{
return (size_t)recv(_conn, (char *)buf, len, 0) == len;
}
bool isConnected()
{
return _connected;
}
};