-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnection.cpp
More file actions
77 lines (65 loc) · 1.68 KB
/
Copy pathConnection.cpp
File metadata and controls
77 lines (65 loc) · 1.68 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
#include "Connection.h"
#include <string>
#include <array>
#include <iostream>
#include "string_util.h"
bool Connection::isHost() const
{
return wasHost;
}
void Connection::listen(int port)
{
sf::TcpListener listener;
if (listener.listen(port) != sf::Socket::Done) {
throw "Was unable to listen to socket";
}
if (listener.accept(socket)) throw "Was unable to connect to socket";
wasHost = true;
}
void Connection::connect(std::string const& ip, int port)
{
while (socket.connect(ip, port) != sf::Socket::Done) {}
}
void Connection::connect(std::vector<std::string> const& ips, int port) {
while (true) {
for (auto& ip : ips) {
if (socket.connect(ip, port) == sf::Socket::Done) {
return;
}
}
}
}
void Connection::disconnect()
{
socket.disconnect();
}
void Connection::send(std::string message)
{
/* if (message.size() > 10000) {
std::cerr << "Messages cannot be over 10,000 characters" << std::endl;
return;
}*/
if (message.size() < 1) {
std::cerr << "Messages must be atleast 1 character" << std::endl;
return;
}
sf::Packet packet;
packet << message;
socket.send(packet);
}
sf::IpAddress Connection::getIp() const
{
return socket.getRemoteAddress();
}
std::pair<std::string, bool> Connection::recieve()
{
sf::Packet packet;
std::string recieved_data;
auto status = socket.receive(packet);
packet >> recieved_data;
return { recieved_data , status != sf::Socket::Status::Disconnected};
}
Connection::~Connection()
{
socket.disconnect();
}