33
|
1 |
|
|
2 |
#include "NetworkSession.hh"
|
|
3 |
|
37
|
4 |
#include <cassert>
|
|
5 |
|
|
6 |
NetworkSession::NetworkSession (uint64_t magic) :
|
33
|
7 |
magic(magic), tcp_srv(NULL), udp_srv(NULL), udp_client(NULL) {
|
|
8 |
|
|
9 |
// nothing
|
|
10 |
}
|
|
11 |
|
|
12 |
void NetworkSession::listen (const NetworkAddress &addr) {
|
|
13 |
assert(tcp_srv == NULL && udp_srv == NULL);
|
|
14 |
|
|
15 |
// create TCP/UDP servers
|
|
16 |
tcp_srv = new NetworkTCPServer(addr);
|
|
17 |
udp_srv = new NetworkUDP(addr);
|
|
18 |
|
|
19 |
// connect signals
|
37
|
20 |
slots.connect(tcp_srv->sig_client(), this, &NetworkSession::on_tcp_client);
|
33
|
21 |
}
|
|
22 |
|
37
|
23 |
NetworkNode *NetworkSession::build_node (NetworkTCPTransport *tcp, NetworkUDP *udp, const NetworkAddress &addr, enum NetworkNodeType type) {
|
36
|
24 |
// XXX: unused
|
|
25 |
(void) type;
|
|
26 |
|
|
27 |
// create node
|
37
|
28 |
return new NetworkNode(*this, tcp, udp, addr);
|
36
|
29 |
}
|
|
30 |
|
33
|
31 |
NetworkNode* NetworkSession::connect (const NetworkAddress &addr) {
|
|
32 |
// create new UDP client if needed
|
|
33 |
if (udp_client == NULL)
|
|
34 |
udp_client = new NetworkUDP();
|
|
35 |
|
|
36 |
// connect
|
|
37 |
NetworkTCPClient *tcp_client = new NetworkTCPClient(addr);
|
36
|
38 |
|
|
39 |
// build client
|
|
40 |
NetworkNode *client_node = build_node(tcp_client, udp_client, addr, NETWORK_NODE_CLIENT_SERVER);
|
33
|
41 |
|
|
42 |
// add to nodes
|
|
43 |
nodes[addr] = client_node;
|
37
|
44 |
|
|
45 |
// return the "server" node
|
|
46 |
return client_node;
|
33
|
47 |
}
|
|
48 |
|
36
|
49 |
void NetworkSession::on_tcp_client (NetworkTCPTransport *tcp_client) {
|
33
|
50 |
// get remote address manually, because NetworkTCPServer doesn't pass it in to us
|
|
51 |
NetworkAddress addr = tcp_client->getRemoteAddress();
|
|
52 |
|
36
|
53 |
// build client
|
37
|
54 |
NetworkNode *client_node = build_node(tcp_client, udp_srv, addr, NETWORK_NODE_SERVER_CLIENT);
|
33
|
55 |
|
|
56 |
// add to nodes
|
|
57 |
nodes[addr] = client_node;
|
|
58 |
|
|
59 |
// fire signals
|
37
|
60 |
_sig_node_connected(client_node);
|
33
|
61 |
}
|
|
62 |
|
36
|
63 |
void NetworkSession::handle_disconnect (NetworkNode *node) {
|
33
|
64 |
// remove from nodes
|
|
65 |
nodes.erase(node->getRemoteAddress());
|
|
66 |
}
|
|
67 |
|
|
68 |
void NetworkSession::send_all (NetworkChannelID channel_id, const NetworkPacket &pkt, bool reliable) {
|
37
|
69 |
send_all_except(channel_id, pkt, NULL, reliable);
|
33
|
70 |
}
|
|
71 |
|
|
72 |
void NetworkSession::send_all_except (NetworkChannelID channel_id, const NetworkPacket &pkt, const NetworkNode *node, bool reliable) {
|
|
73 |
for (std::map<NetworkAddress, NetworkNode*>::iterator it = nodes.begin(); it != nodes.end(); it++) {
|
|
74 |
if (it->second == node)
|
|
75 |
continue;
|
|
76 |
|
|
77 |
it->second->send(channel_id, pkt, reliable);
|
|
78 |
}
|
|
79 |
}
|