File: NetworkThing.hpp

package info (click to toggle)
blockattack 1.4.1%2Bds1-2.1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 6,260 kB
  • ctags: 1,038
  • sloc: cpp: 9,461; ansic: 142; makefile: 38
file content (397 lines) | stat: -rw-r--r-- 14,922 bytes parent folder | download
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
NetworkThing.hpp
Copyright (C) 2007 Poul Sander

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    Poul Sander
    R�veh�jvej 36, V. 1111
    2800 Kgs. Lyngby
    DENMARK
    blockattack@poulsander.com
*/

#if NETWORK

//The network interface
class NetworkThing
{
private:
    ENetAddress address;
    ENetHost * server;
    ENetHost * client;
    ENetPeer *peer;

    BlockGame *bgHome, *bgAway; //Pointers to the two games, so we can call the procedures
    bool weAreAServer, weAreAClient;
    bool weAreConnected;
    bool enemyIsReady;
    bool enemyHasStarted; //If we should have a ready button
    bool gameHasStarted; //If the player is GameOver it might just be because the game hasn't started yet... not if this is true!

public:

    Uint32 theSeed;

    NetworkThing()
    {
        weAreAServer = false;
        weAreAClient = false;
        weAreConnected = false;
        enemyIsReady = false;
        enemyHasStarted = false;
        gameHasStarted = false;
        if (enet_initialize () != 0)
        {
            fprintf (stderr, "An error occurred while initializing ENet.\n");
        }
        else
        {
            cout << "Network is working!" << endl;
        }
        //atexit (enet_deinitialize); in deconstructor
    }

    //This function couses us to remove the connection to the other peer, plus destroying servers
    void ntDisconnect()
    {
        strcpy(bgAway->name,player2name);
        if (weAreConnected || weAreAClient || weAreAServer)
        {
            if (weAreAClient)
            {
                enet_peer_disconnect (peer,0);
                SDL_Delay(20);
                enet_host_destroy(client);
                weAreAClient = false;
                weAreConnected = false;
                enemyHasStarted = false;
            }
            if (weAreAServer)
            {
                enet_host_destroy(server);
                weAreAServer = false;
                weAreConnected = false;
                enemyHasStarted = false;
            }
            //If the game is running then we disconnect, we are considered the looser!
            if ((!bgHome->bGameOver)&&(!bgAway->bGameOver))
            {
                bgAway->setPlayerWon();
                bgHome->SetGameOver();
            }
            gameHasStarted = false;
        }
    };

    //Lets disconnect before we close...
    ~NetworkThing()
    {
        cout << "Network system is going down" << endl;
        ntDisconnect();
        enet_deinitialize(); 
        cout << "Network system went down" << endl;
    }

    void theGameHasStarted()
    {
        gameHasStarted = true;
    }

    //The NetworkThing needs to be able to call the models... here the pointers are set
    void setBGpointers(BlockGame *bg1, BlockGame *bg2)
    {
        bgHome = bg1;
        bgAway = bg2;
    }

    //Starts a server instance
    void startServer()
    {
        if (!weAreAServer)
        {
            ntDisconnect();

            /* Bind the server to the default localhost.     */
            /* A specific host address can be specified by   */
            /* enet_address_set_host (& address, "x.x.x.x"); */

            address.host = ENET_HOST_ANY;
            /* Bind the server to port SERVERPORT. */
            address.port = SERVERPORT;

            server = enet_host_create (& address /* the address to bind the server host to */,
                                       1      /* allow up to 1 clients and/or outgoing connections */,
				       0      /* no channel limit */,
                                       0      /* assume any amount of incoming bandwidth */,
                                       0      /* assume any amount of outgoing bandwidth */);
            if (server == NULL)
            {
                fprintf (stderr,
                         "An error occurred while trying to create an ENet server host.\n");

            }
            else
            {
                weAreAServer = true;
                enemyIsReady = false;
                gameHasStarted = false;
                cout << "Server is listening on port " << SERVERPORT << endl;
            }
        }
    }

    void connectToServer(string server)
    {
        ENetAddress address;
        ENetEvent event;

        enet_address_set_host (& address, server.c_str());
        address.port = SERVERPORT;

        ntDisconnect();
        client = enet_host_create (NULL /* create a client host */,
                                   1 /* only allow 1 outgoing connection */,
				   0 /* no channel limit */,
                                   0 /* Unlimited downstream bandwidth */,
                                   0 /* Unlimted upstream bandwidth */);

        if (client == NULL)
        {
            cout << "An error occurred while trying to create an ENet client host." << endl;
        }
        else
        {
            /* Initiate the connection, allocating the four channels 0 and 1 and 2 and 3. */
            peer = enet_host_connect (client, & address, 4, 0);

            if (peer == NULL)
            {
                cout << "No available peers for initiating an ENet connection." << endl;
            }
            else
                if (enet_host_service (client, & event, 2000) > 0 &&
                        event.type == ENET_EVENT_TYPE_CONNECT)
                {
                    cout << "We are connected!" << endl;
                    enemyIsReady = false;
                    weAreAClient = true;
                    weAreConnected = true;
                    gameHasStarted = false;
                }
                else
                {
                    cout << "Server didn't answer in time" << endl;
                }
        }
    }

    bool isConnected()
    {
        return (weAreConnected||weAreAServer);
    }

    bool isConnectedToPeer()
    {
        return weAreConnected;
    }

    //This function must be called in the game loop:
    void updateNetwork()
    {
        //Now we must send our own board:
        if (weAreConnected)
        {
            //cout << "Creating package" << endl;
            boardPackage boardpack = bgHome->getPackage();
            ENetPacket * packet = enet_packet_create (&boardpack,
                                  sizeof(boardPackage),
                                  0);
            //Now lets send the package
            if (weAreAServer)
                enet_host_broadcast (server, 0, packet);
            else
                if (weAreAClient)
                    enet_peer_send (peer, 0, packet);
            //cout << "Package sent" << endl;

            //See if we are game over and in that case notify the other player
            if ((gameHasStarted)&&(bgHome->bGameOver))
            {
                ENetPacket * packet = enet_packet_create("G",2,ENET_PACKET_FLAG_RELIABLE);
                if (weAreAServer)
                    enet_host_broadcast (server, 1, packet);
                else
                    if (weAreAClient)
                        enet_peer_send (peer, 1, packet);
                gameHasStarted=false;
            }

            //Now lets see if we have something to throw at the opponent.
            Uint8 x,y,type;

            if (gameHasStarted)
                while (bgAway->popGarbage(&x,&y,&type))
                { //if there are garbage to drop
                    if (type==1)
                    {
                        x=255;
                        y=255;
                    }
                    Uint16 g = ((Uint16)x)*256+(Uint16)y; //A 16-bit int containing everything
                    ENetPacket * packet = enet_packet_create(&g,2,ENET_PACKET_FLAG_RELIABLE);
                    if (weAreAServer)
                        enet_host_broadcast (server, 2, packet);
                    else
                        if (weAreAClient)
                            enet_peer_send (peer, 2, packet);
                    cout << "We send a garbage block: " << (int)x << "," << (int)y << "==" << g << endl;
                }
        }
        ENetEvent event;

        /* Wait up to 0 milliseconds for an event. */
        while (((weAreAClient)&&(enet_host_service (client, & event, 0) > 0))||((weAreAServer)&&(enet_host_service (server, & event, 0) > 0)))
        {
            switch (event.type)
            {
            case ENET_EVENT_TYPE_CONNECT:
                printf ("A new client connected from %x:%u.\n",
                        event.peer -> address.host,
                        event.peer -> address.port);
                weAreConnected = true;
                /* Store any relevant client information here. */
                //event.peer -> data = "Client";
                {

                    ENetPacket * namePacket = enet_packet_create(bgHome->name,sizeof(char[30]),ENET_PACKET_FLAG_RELIABLE);
                    //if(weAreAServer)
                    enet_host_broadcast (server, 3, namePacket);
                    ENetPacket * answerPacket = enet_packet_create("version3",sizeof("version3"),ENET_PACKET_FLAG_RELIABLE);
                    enet_host_broadcast (server, 3, answerPacket);
                    theSeed = time(0)/4;
                    bgHome->putStartBlocks(theSeed);
                    ENetPacket * timePacket = enet_packet_create(&theSeed,sizeof(theSeed),ENET_PACKET_FLAG_RELIABLE);
                    enet_host_broadcast (server, 3, timePacket);
                    cout << "We send the seed: " << theSeed << endl;
                }
                break;

            case ENET_EVENT_TYPE_RECEIVE:
                /*printf ("A packet of length %u containing %s was received from %s on channel %u.\n",
                    event.packet -> dataLength,
                    event.packet -> data,
                    event.peer -> data,
                    event.channelID);*/
                //cout << "Package received" << endl;
                if (event.channelID==0) //Unreliable (only boardPacks)
                {
                    boardPackage bpack;
                    //cout << "Package size: "<< event.packet->dataLength << " should be: " << sizeof(boardPackage) << endl;
                    memcpy(&bpack,(const char*)event.packet->data,sizeof(boardPackage));
                    bgAway->setBoard(bpack);
                }
                if (event.channelID==1) //reliable (used for GameOver notifications only!)
                {
                    if ((bgHome->bGameOver)&&(!bgHome->hasWonTheGame)&&(gameHasStarted))
                    {
                        bgHome->setDraw();
                        bgAway->setDraw();
                    }
                    else
                    {
                        bgHome->setPlayerWon();
                        bgAway->SetGameOver();
                    }
                    gameHasStarted=false;
                }

                if (event.channelID==2) //reliable (used for Garbage only!)
                {
                    Uint16 g;
                    memcpy(&g,event.packet->data,sizeof(Uint16));
                    Uint8 x = (g/256);
                    Uint8 y = (g%256);
                    cout << "Received Garbage: " << (int)x << "," << (int)y << endl;
                    if ((x==255)&&(y==255))
                        bgHome->CreateGreyGarbage();
                    else
                        bgHome->CreateGarbage(x,y);
                }

                if (event.channelID==3) //We have reacieved a name or a version number
                {
                    if (event.packet->dataLength==sizeof(char[30])) //We have reveived a name
                    {
                        strcpy(bgAway->name,(const char*)event.packet->data);
                        cout << "The enemy name is: " << bgAway->name << " Length: " << sizeof(char[30])<< endl;
                        if (weAreAClient) //We have just received the servers name and must send our own
                        {
                            ENetPacket * answerPacket = enet_packet_create(bgHome->name,sizeof(char[30]),ENET_PACKET_FLAG_RELIABLE);
                            enet_peer_send (peer, 3, answerPacket);
                        }
                    }
                    else
                        if (event.packet->dataLength==sizeof("version3")) //We have received aversion number
                        {
                            if (0!=strcmp((const char*)event.packet->data,"version3"))
                            {
                                cout << "Incompatible version: " << event.packet->data << "!=" << "version3" << endl;
                                ntDisconnect();
                            }
                            if (weAreAClient) //We will send our version number
                            {
                                ENetPacket * answerPacket = enet_packet_create("version3",sizeof("version3"),ENET_PACKET_FLAG_RELIABLE);
                                enet_peer_send (peer, 3, answerPacket);
                            }
                        }
                        else
                            if (event.packet->dataLength==sizeof(Uint32)) //We have received a seed
                            {
                                memcpy(&theSeed,event.packet->data,sizeof(Uint32));
                                bgHome->putStartBlocks(theSeed);
                                cout << "We received a seed: " << theSeed << endl;
                            }
                }

                /* Clean up the packet now that we're done using it. */
                enet_packet_destroy (event.packet);

                break;

            case ENET_EVENT_TYPE_DISCONNECT:
                //printf ("%s disconected.\n", event.peer -> data);
                cout << event.peer -> data << " disconnected." << endl;

                /* Reset the peer's client information. */

                event.peer -> data = NULL;
                //weAreConnected = false;
                if ((!bgHome->bGameOver)&&(!bgAway->bGameOver))
                {
                    bgHome->setPlayerWon();
                    bgAway->SetGameOver();
                }

                ntDisconnect(); //When we will disconnect!

            }
        }


    }
}; //NetworkThing

#endif