2 Copyright (C) 2008 Mathias Gottschlag
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in the
6 Software without restriction, including without limitation the rights to use,
7 copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
8 Software, and to permit persons to whom the Software is furnished to do so,
9 subject to the following conditions:
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
15 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
16 PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
17 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
18 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
19 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 #include "network/NetworkHost.h"
23 #include "network/Connection.h"
24 #include "core/Logger.h"
30 NetworkHost::NetworkHost()
34 NetworkHost::~NetworkHost()
38 bool NetworkHost::init(int port
)
40 // Create network host
42 address
.host
= ENET_HOST_ANY
;
44 host
= enet_host_create(&address
, 32, 200000, 20000);
47 LERROR("Could not create network host.\n");
50 LINFO("Created network host.\n");
53 bool NetworkHost::shutdown(void)
55 for (unsigned int i
= 0; i
< connections
.size(); i
++)
57 Connection
*conn
= connections
[i
];
59 delete connections
[i
];
63 enet_host_destroy(host
);
68 Connection
*NetworkHost::getNewConnection(void)
70 if (newconnections
.empty())
75 Connection
*conn
= newconnections
.front();
79 void NetworkHost::closeConnection(Connection
*conn
)
81 for (unsigned int i
= 0; i
< connections
.size(); i
++)
83 if (connections
[i
] == conn
)
85 connections
[i
]->destroy();
86 delete connections
[i
];
87 connections
.erase(connections
.begin() + i
);
93 bool NetworkHost::doWork(void)
101 while (enet_host_service(host
, &event
, 0) > 0)
105 case ENET_EVENT_TYPE_CONNECT
:
107 LINFO("Host: Someone connected.\n");
108 Connection
*newconn
= new Connection(event
.peer
);
109 connections
.push_back(newconn
);
110 newconnections
.push(newconn
);
113 case ENET_EVENT_TYPE_RECEIVE
:
114 //printf("Host: Received data.\n");
115 // Push received data into connection
116 for (unsigned int i
= 0; i
< connections
.size(); i
++)
118 if (event
.peer
== connections
[i
]->getPeer())
120 Buffer
*buffer
= new Buffer
;
121 buffer
->writeData(event
.packet
->data
,
122 event
.packet
->dataLength
, true);
123 connections
[i
]->injectData(buffer
);
127 case ENET_EVENT_TYPE_DISCONNECT
:
128 LINFO("Host: Someone disconnected.\n");
129 for (unsigned int i
= 0; i
< connections
.size(); i
++)
131 if (event
.peer
== connections
[i
]->getPeer())
133 connections
[i
]->destroy();