-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetClient.cpp
1760 lines (1566 loc) · 61 KB
/
NetClient.cpp
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 RWS Inc, All Rights Reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of version 2 of the GNU General Public License as published by
// the Free Software Foundation
//
// 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.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// NetClient.cpp
// Project: RSPiX
//
// History:
// 09/01/97 MJR Nearing the end of a major overhaul.
//
// 09/07/97 MJR Fixed problem with DROPPED message, whereby the caller
// couldn't recognize when he himself was dropped because
// the ID was no longer valid.
//
// Added support for PROCEED and PROGRESS_REALM messages.
//
// 09/10/97 MJR Changed return value from StartJoinProcess() so that
// caller could determine whether the failure was due to
// unsupported protocol (RSocket::errNotSupported).
//
// 09/12/97 MJR Added SendText() as alternative to SendChat().
//
// 09/12/97 MJR Now checks to make sure we're joined before it tries to
// send chat or text.
//
// 11/25/97 JMI Changed m_error to m_msgError so we could store a whole
// error message instead of just the error type.
// Also, now notices the difference between a version mismatch
// and a platform mismatch and reports separate errors for
// each.
//
// 11/26/97 JMI Masking error in evaluation of version mismatch problem
// such that platform mismatch was never detected.
//
// 12/18/97 SPA Changed ReceiveFromPeers to limit by number of times through
// the loop (to number of joined peers *2) instead of a time limit.
// Changed SendToPeers to write it's own data directly instead of
// sending it out over the net just to receive it again later.
// Also limited the resending of the same packet multiple times
// to a maximum number (set from prefs - NumSendsPerBurst - default 2)
// and a repeat interval for burst (set from prefs - SendInterval -
// default 1000 ms).
// Added variable frame rate (really more of a self regulating frame rate).
// Each peer keeps track of how long it took between frames (as measured
// in CanDoFrame) and then sends that value to all other peers in the
// next available frame that hasn't been yet. Each peer then averages the
// frame times for that frame (which is really the time it took for the
// frame that happened MaxFrameLag frames ago). This is stored in an array
// which contains the average frame times for the last eight frames. The
// values in this array are then averaged and the result is used as the
// elapsed game time for the current frame (passed back in psFrameTime).
// This last step is done to smooth out any rapid changes in the speed.
// Also changed msg INPUT_REQ and INPUT_DATA to update frame time from above.
//
// 12/22/97 SPA Rewrote SendToPeers to send only one packet per frame with each packet
// containing all the frames that that peer might need. This is frames
// starting from the previous frame (which is the one that we have all
// the data for) minus MaxFrameLag up to current frame plus MaxFrameLag.
// This means that we send (MaxFrameLag *2 + 2) frames per packet. This also
// means that each frame is sent (MaxFrameLag *2 + 2) times which should
// replace most lost or misplaced packets. In case we do loose multiple
// packets, there is also a request mechanism. If we are unable to render
// a frame after a time out has expired, we request frame data from the
// peers that are missing (as well as resending the last packet sent to
// them, just in case the reason he didn't send the data is because he
// didn't get our data). The request is checked for in ReceiveFromPeers
// and the requested data sent immediately. To simplify the request mechanism
// I pulled the center loop of SendToPeers out into it's own method (SendToPeer).
//
// 1/5/98 SPA Fixed problem were we would not go to next level because the data for the
// halt frame was not being sent so that everyone was stuck waiting to
// render the last frame.
//
// 1/6/98 SPA TimePerFrame from .ini now used for maximum time per frame instead of actual
// time per frame. SendInputInterval from .ini now used as timeout value for
// frame request mechanism.
//
// 06/02/98 JMI Added an additional condition to avoid indexing into the
// peers array with our ID when it is invalid in
// SetLocalInput().
//
////////////////////////////////////////////////////////////////////////////////
#include "RSPiX.h"
#include "netclient.h"
#include "NetDlg.h"
// This is the maximum size of the peer messages.
#define PEER_MSG_HEADER_SIZE (1 + 2 + 2 + 2 + 2)
#define PEER_MSG_MAX_SIZE (PEER_MSG_HEADER_SIZE + ((Net::MaxAheadSeq * 2) * (sizeof(UINPUT) + sizeof(U8)))) // *SPA
////////////////////////////////////////////////////////////////////////////////
// Get values from buffer in proper endian order (buffer contents are always
// in network order, which is big-endian).
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
// Get a U8
//------------------------------------------------------------------------------
inline void Get(U8* &pget, U8* pval)
{
*pval = *pget++;
}
//------------------------------------------------------------------------------
// Get an S8
//------------------------------------------------------------------------------
inline void Get(U8* &pget, S8* pval)
{
Get(pget, (U8*)pval);
}
//------------------------------------------------------------------------------
// Get a U16
//------------------------------------------------------------------------------
inline void Get(U8* &pget, U16* pval)
{
#ifdef SYS_ENDIAN_LITTLE
U8* ptmp = ((U8*)(pval)) + 1;
*ptmp-- = *pget++;
*ptmp = *pget++;
#else
U8* ptmp = (U8*)(pval);
*ptmp++ = *pget++;
*ptmp = *pget++;
#endif
}
//------------------------------------------------------------------------------
// Get an S16
//------------------------------------------------------------------------------
inline void Get(U8* &pget, S16* pval)
{
Get(pget, (U16*)pval);
}
//------------------------------------------------------------------------------
// Get a U32
//------------------------------------------------------------------------------
inline void Get(U8* &pget, U32* pval)
{
#ifdef SYS_ENDIAN_LITTLE
U8* ptmp = ((U8*)(pval)) + 3;
*ptmp-- = *pget++;
*ptmp-- = *pget++;
*ptmp-- = *pget++;
*ptmp = *pget++;
#else
U8* ptmp = (U8*)(pval);
*ptmp++ = *pget++;
*ptmp++ = *pget++;
*ptmp++ = *pget++;
*ptmp = *pget++;
#endif
}
//------------------------------------------------------------------------------
// Get a U64
//------------------------------------------------------------------------------
inline void Get(U8* &pget, U64* pval)
{
#ifdef SYS_ENDIAN_LITTLE
U8* ptmp = ((U8*)(pval)) + 3;
*ptmp-- = *pget++;
*ptmp-- = *pget++;
*ptmp-- = *pget++;
*ptmp-- = *pget++;
*ptmp-- = *pget++;
*ptmp-- = *pget++;
*ptmp-- = *pget++;
*ptmp = *pget++;
#else
U8* ptmp = (U8*)(pval);
*ptmp++ = *pget++;
*ptmp++ = *pget++;
*ptmp++ = *pget++;
*ptmp++ = *pget++;
*ptmp++ = *pget++;
*ptmp++ = *pget++;
*ptmp++ = *pget++;
*ptmp = *pget++;
#endif
}
//------------------------------------------------------------------------------
// Get an S32
//------------------------------------------------------------------------------
inline void Get(U8* &pget, S32* pval)
{
Get(pget, (U32*)pval);
}
////////////////////////////////////////////////////////////////////////////////
// Put values into buffer in proper endian order (buffer contents are always
// in network order, which is big-endian).
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
// Put a U8
//------------------------------------------------------------------------------
inline void Put(U8* &pput, U8 val)
{
*pput++ = val;
}
//------------------------------------------------------------------------------
// Put an S8
//------------------------------------------------------------------------------
inline void Put(U8* &pput, S8 val)
{
Put(pput, (U8)val);
}
//------------------------------------------------------------------------------
// Put a U16
//------------------------------------------------------------------------------
inline void Put(U8* &pput, U16 val)
{
#ifdef SYS_ENDIAN_LITTLE
U8* ptmp = ((U8*)(&val)) + 1;
*pput++ = *ptmp--;
*pput++ = *ptmp;
#else
U8* ptmp = (U8*)(&val);
*pput++ = *ptmp++;
*pput++ = *ptmp;
#endif
}
//------------------------------------------------------------------------------
// Put an S16
//------------------------------------------------------------------------------
inline void Put(U8* &pput, S16 val)
{
Put(pput, (U16)val);
}
//------------------------------------------------------------------------------
// Put a U32
//------------------------------------------------------------------------------
inline void Put(U8* &pput, U32 val)
{
#ifdef SYS_ENDIAN_LITTLE
U8*ptmp = ((U8*)(&val)) + 3;
*pput++ = *ptmp--;
*pput++ = *ptmp--;
*pput++ = *ptmp--;
*pput++ = *ptmp;
#else
U8*ptmp = (U8*)(&val);
*pput++ = *ptmp++;
*pput++ = *ptmp++;
*pput++ = *ptmp++;
*pput++ = *ptmp;
#endif
}
//------------------------------------------------------------------------------
// Put a U64
//------------------------------------------------------------------------------
inline void Put(U8* &pput, U64 val)
{
#ifdef SYS_ENDIAN_LITTLE
U8*ptmp = ((U8*)(&val)) + 3;
*pput++ = *ptmp--;
*pput++ = *ptmp--;
*pput++ = *ptmp--;
*pput++ = *ptmp--;
*pput++ = *ptmp--;
*pput++ = *ptmp--;
*pput++ = *ptmp--;
*pput++ = *ptmp;
#else
U8*ptmp = (U8*)(&val);
*pput++ = *ptmp++;
*pput++ = *ptmp++;
*pput++ = *ptmp++;
*pput++ = *ptmp++;
*pput++ = *ptmp++;
*pput++ = *ptmp++;
*pput++ = *ptmp++;
*pput++ = *ptmp;
#endif
}
//------------------------------------------------------------------------------
// Put an S32
//------------------------------------------------------------------------------
inline void Put(U8* &pput, S32 val)
{
Put(pput, (U32)val);
}
////////////////////////////////////////////////////////////////////////////////
// Startup
////////////////////////////////////////////////////////////////////////////////
void CNetClient::Startup(
RSocket::BLOCK_CALLBACK callback) // In: Blocking callback
{
// Do a reset to be sure we're starting at a good point
Reset();
// Save callback
m_callback = callback;
}
////////////////////////////////////////////////////////////////////////////////
// Shutdown
////////////////////////////////////////////////////////////////////////////////
void CNetClient::Shutdown(void)
{
Reset();
}
////////////////////////////////////////////////////////////////////////////////
// Start the process of joining the game on the specified host. The port in
// in the host's address is assumed to be the so-called "base port".
//
// If this function returns an error, it indicates that the join process has
// failed, most likely because the currently selected protocol is not supported.
// Even if this happens, it is still safe to call Update() and GetMsg() as if
// no error occurred, realizing, of course, that the join process will not
// succeed and GetMsg() will shortly return an error to that effect.
////////////////////////////////////////////////////////////////////////////////
short CNetClient::StartJoinProcess( // Returns 0 if successfull, non-zero otherwise
RSocket::Address* paddressHost, // In: Host's address
char* pszName, // In: Joiner's name
unsigned char ucColor, // In: Joiner's color
unsigned char ucTeam, // In: Joiner's team
short sBandwidth) // In: Joiner's Net::Bandwidth
{
// Save server address (containing the base port)
m_addressServer = *paddressHost;
// Calculate server's listen address (the port is simply offset from the base port)
m_addressServerListen = *paddressHost;
RSocket::SetAddressPort(RSocket::GetAddressPort(&m_addressServer) + Net::ListenPortOffset, &m_addressServerListen);
// Temporarily stash the join data in peer #0
memcpy(m_aPeers[0].m_acName, pszName, sizeof(m_aPeers[0].m_acName));
m_aPeers[0].m_acName[sizeof(m_aPeers[0].m_acName)-1] = 0;
m_aPeers[0].m_ucColor = ucColor;
m_aPeers[0].m_ucTeam = ucTeam;
m_aPeers[0].m_sBandwidth = sBandwidth;
// Start the asynchronous connection process. If an error is returned, it's
// never going to succeed. If it doesn't return an error, we poll m_msgr's
// state in Update() to determine whether it failed or succeeded. We also
// set a timer so that if it takes too long, we'll give up.
// NOTE: Even though the caller could obviously check the result and not
// bother calling Update() if the result indicates failure, we do allow
// for the caller to ignore the value and go right into the normal "loop"
// which includes calling Update() and GetMsg(), so they can handle errors
// the "normal" way -- via GetMsg().
short sResult = m_msgr.Connect(&m_addressServerListen, m_callback);
m_state = WaitForConnect;
m_lTimeOut = rspGetMilliseconds() + Net::MaxConnectWaitTime;
return sResult;
}
////////////////////////////////////////////////////////////////////////////////
// Update (must be called regularly)
////////////////////////////////////////////////////////////////////////////////
void CNetClient::Update(void)
{
NetMsg msg;
// If there's an error message that the user hasn't retrieved yet, then
// we can't do anything.
if (m_msgError.msg.err.error == NetMsg::NoError)
{
switch (m_state)
{
case Nothing:
// Nothing to do
break;
case WaitForConnect:
// Wait for connect attempt to complete or fail or timeout
m_msgr.Update();
switch(m_msgr.GetState())
{
case CNetMsgr::Connecting:
if (rspGetMilliseconds() > m_lTimeOut)
{
TRACE("CNetClient::Update(): Timed-out trying to connect to server!\n");
m_msgError.msg.err.error = NetMsg::ConnectTimeoutError;
Drop();
}
break;
case CNetMsgr::Connected:
// Send login message to server and set state to wait for response
msg.msg.login.ucType = NetMsg::LOGIN;
msg.msg.login.ulMagic = CNetMsgr::MagicNum;
msg.msg.login.ulVersion = CNetMsgr::CurVersionNum;
SendMsg(&msg);
m_state = WaitForLoginResponse;
m_status = NetMsg::Connected;
break;
case CNetMsgr::Disconnecting:
case CNetMsgr::Disconnected:
default:
TRACE("CNetClient::Update(): Error trying to connect to server!\n");
m_msgError.msg.err.error = NetMsg::CantConnectError;
Drop();
break;
}
break;
case WaitForLoginResponse:
// Wait for response to our LOGIN message
m_msgr.Update();
m_msgr.GetMsg(&msg);
msg.ucSenderID = Net::InvalidID;
switch(msg.msg.nothing.ucType)
{
case NetMsg::NOTHING:
break;
case NetMsg::LOGIN_ACCEPT:
////////////////////////////////////////////////////////////////
// Version negotiation and useful error results ////////////////
////////////////////////////////////////////////////////////////
//
// In net implementation for Postal net version 1, both the
// server and the client would check the version numbers -- the
// server would check msg.login.ulVersion against its
// MinVersionNum & CurVersionNum and, if the server accepted the
// login, the client would check msg.loginAccept.ulVersion
// against its MinVersionNum & CurVersionNum. Although the
// version 1 client would display an error message when it
// decided it could not support the server's version, the server
// would refuse a login before that, never giving the client a
// chance to notice and report this to the user.
// To remedy this, the Postal Net version 2's server NEVER
// rejects a client and, instaed, relies on the client to reject
// it. This gives the client a chance to report the error.
// Since under our new scheme we never send a LOGIN_DENY, we
// know, if we receive a LOGIN_DENY, that we are dealing with a
// version 1 server.
//
// Additionally, bit fifteen of the version number is set if on
// a Mac platform so we can use the same mechanism to determine
// if we are attempting to connect a Mac and a PC.
//
// Here's the actual scenarios and results for version conflicts:
//
// Server 1 vs Client 2 -- Server sends Client a LOGIN_DENY so
// the client knows it's dealing with a version 1 server and
// reports the problem.
//
// Server 2 vs Client 1 -- Server accepts connection. Client
// drops, though, when it sees the server's version is 2 and
// reports the problem.
//
// For future versions:
//
// Server 3 vs Client 1 -- Server accepts connection. Client
// drops, though, when it sees the server's version is 3 and
// reports the problem.
//
// Server 3 vs Client 2 -- Server accepts connection. Client
// drops, though, when it sees the server's version is 3 and
// reports the problem.
//
// (see NetMsg::LOGIN_DENY case for handling of net version 1)
//
////////////////////////////////////////////////////////////////
// Check server's version number to see if we can support it
if ( (msg.msg.loginAccept.ulVersion >= CNetMsgr::MinVersionNum) && (msg.msg.loginAccept.ulVersion <= CNetMsgr::CurVersionNum))
{
// Save our assigned ID
m_id = msg.msg.loginAccept.idAssigned;
// Send join request and set state to wait for response. After this point, we no
// longer care about the data we temporarily stashed in peer #0 because if our join
// request is accepted, the server will send us info about ALL the clients, including
// ourself. If our request is denied, then nothing matters.
msg.msg.joinReq.ucType = NetMsg::JOIN_REQ;
memcpy(msg.msg.joinReq.acName, m_aPeers[0].m_acName, sizeof(msg.msg.joinReq.acName));
msg.msg.joinReq.ucColor = m_aPeers[0].m_ucColor;
msg.msg.joinReq.ucTeam = m_aPeers[0].m_ucTeam;
msg.msg.joinReq.sBandwidth = m_aPeers[0].m_sBandwidth;
SendMsg(&msg);
m_state = WaitForJoinResponse;
m_status = NetMsg::LoginAccepted;
}
else
{
// Determine error type (possibilities are incompatible
// versions and/or incompatible platforms).
if ( (msg.msg.loginAccept.ulVersion & CNetMsgr::MacVersionBit) ^ (CNetMsgr::MinVersionNum & CNetMsgr::MacVersionBit) )
{
// One of us is a Mac and one is a PC.
m_msgError.msg.err.error = NetMsg::ClientPlatformMismatchError;
}
else
{
// Incompatible version number.
m_msgError.msg.err.error = NetMsg::ClientVersionMismatchError;
m_msgError.msg.err.ulParam = msg.msg.loginAccept.ulVersion & ~CNetMsgr::MacVersionBit;
}
// Unsupported version number -- send LOGOUT message
msg.msg.logout.ucType = NetMsg::LOGOUT;
SendMsg(&msg);
Drop();
TRACE("CNetClient::Update(): Error trying to login to server -- unsupported version number!\n");
}
break;
case NetMsg::LOGIN_DENY:
Drop();
// There's ONLY ONE reason we'll ever get a LOGIN_DENY message and that is
// a version 1 server refused our connection b/c of our later version number
// so ... Incompatible version number.
m_msgError.msg.err.error = NetMsg::ClientVersionMismatchError;
m_msgError.msg.err.ulParam = 1;
// m_msgError.msg.err.error = NetMsg::LoginDeniedError;
TRACE("CNetClient::Update(): Login denied!\n");
break;
default:
TRACE("CNetClient::Update(): Unexpected message received while waiting for login response!\n");
break;
}
break;
case WaitForJoinResponse:
// Wait for response to our JOIN_REQ message
m_msgr.Update();
m_msgr.GetMsg(&msg);
msg.ucSenderID = Net::InvalidID;
switch(msg.msg.nothing.ucType)
{
case NetMsg::NOTHING:
break;
case NetMsg::JOIN_ACCEPT:
{
// Calculate our peer port based on the server's base port
unsigned short usPeerPort = RSocket::GetAddressPort(&m_addressServer) + Net::FirstPeerPortOffset + m_id;
// Open peer socket (this is an unconnected datagram socket, so all the peers
// simply hurl their data at this port, and we figure out who it came from).
if (m_socketPeers.Open(usPeerPort, RSocket::typDatagram, RSocket::optDontBlock, m_callback) == 0)
{
// We are now fully joined. HOWEVER, we don't adjust the m_sNumJoined here
// because we want to allow the server to be in direct control of that by
// virtue of JOINED and DROPPED messages.
m_state = Joined;
m_status = NetMsg::JoinAccepted;
}
else
{
Drop();
m_msgError.msg.err.error = NetMsg::CantOpenPeerSocketError;
TRACE("CNetClient::Update(): Error opening port!\n");
}
}
break;
case NetMsg::JOIN_DENY:
Drop();
m_msgError.msg.err.error = NetMsg::JoinDeniedError;
TRACE("CNetClient::Update(): Join denied!\n");
break;
default:
TRACE("CNetClient::Update(): Unexpected message received while waiting for join response!\n");
break;
}
break;
case Joined:
// Update messenger to server
m_msgr.Update();
// Always try receiving from peers before sending, because the data we
// receive can influence the data we'll send.
ReceiveFromPeers();
SendToPeers();
// If nothing was sent in a while, do a ping to tell server we're still alive
#if NET_PING
if ((rspGetMilliseconds() - m_msgr.GetMostRecentMsgSentTime()) > MaxTimeBetweenSends)
{
// Send ping msg
msg.msg.ping.ucType = NetMsg::PING;
msg.msg.ping.lTimeStamp = rspGetMilliseconds();
msg.msg.ping.lLatestPingResult = m_lLatestPingResult;
SendMsg(&msg);
}
#endif
break;
default:
TRACE("CNetClient::Update(): Unknown state!\n");
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Get next available message from server
////////////////////////////////////////////////////////////////////////////////
void CNetClient::GetMsg(
NetMsg* pmsg) // Out: Message is returned here
{
// This indicates whether we got a message to be returned to the caller
bool bGotMsgForCaller = false;
if (m_msgError.msg.err.error != NetMsg::NoError)
{
// If an error occurred, generate an error message, then reset the error flag
*pmsg = m_msgError;
bGotMsgForCaller = true;
m_msgError.msg.err.error = NetMsg::NoError;
m_msgError.msg.err.ulParam = 0;
// Return this message to caller
bGotMsgForCaller = true;
}
else if (m_status != NetMsg::NoStatus)
{
// If a status occurred, generate a status message, then reset the status flag
pmsg->msg.stat.ucType = NetMsg::STAT;
pmsg->msg.stat.status = m_status;
bGotMsgForCaller = true;
m_status = NetMsg::NoStatus;
// Return this message to caller
bGotMsgForCaller = true;
}
else if (m_state == Joined)
{
// If we're waiting for the end the of the realm and we've reached the halt
// frame, then we generate a NEXT_REALM message for the caller.
if (m_bNextRealmPending && m_bReachedHaltFrame)
{
// Clear the flags
m_bUseHaltFrame = false;
m_bNextRealmPending = false;
m_bReachedHaltFrame = false;
// Create NEXT_REALM message (note that seqHalt is meaningless to caller)
pmsg->msg.nextRealm.ucType = NetMsg::NEXT_REALM;
pmsg->msg.nextRealm.seqHalt = 0;
// Return this message to caller
bGotMsgForCaller = true;
}
else
{
// If we're in the joined state, get the next message from the server and
// fill in the sender ID (it's always the server, which is Net::InvalidID)
m_msgr.GetMsg(pmsg);
pmsg->ucSenderID = Net::InvalidID;
switch (pmsg->msg.nothing.ucType)
{
case NetMsg::NOTHING:
break;
case NetMsg::STAT:
// Return this message to caller
bGotMsgForCaller = true;
break;
case NetMsg::ERR:
// If an error occurs, there's no way to recover, so we have to drop.
// The drop may not fully work if there's a problem communicating with
// the server, but there's no harm in trying.
TRACE("CNetClient::GetMsg(): Error message received from messenger!\n");
Drop();
// Return this message to caller
bGotMsgForCaller = true;
break;
case NetMsg::JOINED:
{
// Get id and verify that it's unused
Net::ID id = pmsg->msg.joined.id;
ASSERT(m_aPeers[id].m_state == CPeer::Unused);
// Save this peer's info
m_aPeers[id].m_address = pmsg->msg.joined.address;
memcpy(m_aPeers[id].m_acName, pmsg->msg.joined.acName, sizeof(m_aPeers[id].m_acName));
m_aPeers[id].m_ucColor = pmsg->msg.joined.ucColor;
m_aPeers[id].m_ucTeam = pmsg->msg.joined.ucTeam;
// Change state to "joined"
m_aPeers[id].m_state = CPeer::Joined;
// Adjust number of joined peers. Note that we rely fully on the server to send the
// appropriate JOINED and DROPPED messages -- if it screws up, our number will be off.
m_sNumJoined++;
// Return this message to caller
bGotMsgForCaller = true;
}
break;
case NetMsg::CHANGED:
{
// Get id and verify that it's joined
Net::ID id = pmsg->msg.changed.id;
ASSERT(m_aPeers[id].m_state == CPeer::Joined);
// Change this peer's info
memcpy(m_aPeers[id].m_acName, pmsg->msg.changed.acName, sizeof(m_aPeers[id].m_acName));
m_aPeers[id].m_ucColor = pmsg->msg.changed.ucColor;
m_aPeers[id].m_ucTeam = pmsg->msg.changed.ucTeam;
// Return this message to caller
bGotMsgForCaller = true;
}
break;
case NetMsg::DROPPED:
{
// Get id and verify that it's joined
Net::ID id = pmsg->msg.dropped.id;
ASSERT(m_aPeers[id].m_state == CPeer::Joined);
// If it was me that was dropped, it's a different case
if (id == m_id)
{
// We're done playing
m_bPlaying = false;
// Disconnect cleanly
m_msgr.Disconnect(true);
// Clear net ID
m_id = Net::InvalidID;
// Reset state
m_state = Nothing;
// Since we cleared our own ID, the caller will no longer be able to
// recognize himself, because the ID in the message will not match
// our own ID. Instead, we change the ID in the message to Net::InvalidID
// as a flag that indicates "you yourself have been dropped".
pmsg->msg.dropped.id = Net::InvalidID;
}
else
{
// If the game has started, dropping is easy. Otherwise, we merely
// kick off the beginning of a long sequence...
if (pmsg->msg.dropped.sContext == -1)
{
// Change specified peer's state to "unused"
m_aPeers[id].m_state = CPeer::Unused;
}
else
{
// Change specified peer's state to "dropped"
m_aPeers[id].m_state = CPeer::Dropped;
// Stop playing until we get a START_REALM, which the server
// will send when the drop process is completely done.
m_bPlaying = false;
// Respond with a DROP_ACK message that tells the server what frame
// we're on and the last input seq we got from the dropee.
NetMsg msg;
msg.msg.dropAck.ucType = NetMsg::DROP_ACK;
msg.msg.dropAck.seqLastDropeeInput = (Net::SEQ)(m_aPeers[id].m_netinput.FindFirstInvalid() - (Net::SEQ)1);
msg.msg.dropAck.seqLastDoneFrame = (Net::SEQ)(m_seqFrame - (Net::SEQ)1);
SendMsg(&msg);
}
}
// Adjust number of joined peers. Note that we rely fully on the server to send
// appropriate JOINED and DROPPED messages -- if it screws up, our number will be off.
m_sNumJoined--;
// Return this message to caller
bGotMsgForCaller = true;
}
break;
case NetMsg::INPUT_REQ:
{
// Get id
Net::ID id = pmsg->msg.inputReq.id;
// In response to this, we need to generate an INPUT_DATA message, which is a
// variable-size message. We'll have the message allocate memory for the
// input data, which is what varies in size. It will free the memory when it
// gets destroyed.
NetMsg msg;
msg.msg.inputData.ucType = NetMsg::INPUT_DATA;
msg.msg.inputData.id = id;
msg.msg.inputData.seqStart = pmsg->msg.inputReq.seqStart;
msg.msg.inputData.sNum = pmsg->msg.inputReq.sNum;
msg.msg.inputData.pInputs = (UINPUT*)msg.AllocVar((long)pmsg->msg.inputReq.sNum * sizeof(UINPUT));
msg.msg.inputData.pFrameTimes = (U8*)msg.AllocVar((long)pmsg->msg.inputReq.sNum * sizeof(U8));
// Copy the requested values into the allocated memory
Net::SEQ seq = msg.msg.inputData.seqStart;
for (short s = 0; s < msg.msg.inputData.sNum; s++)
{
msg.msg.inputData.pFrameTimes[s] = m_aPeers[id].m_netinput.GetFrameTime(seq); // *SPA
msg.msg.inputData.pInputs[s] = m_aPeers[id].m_netinput.Get(seq++);
}
// Send to server. We force this to send immediately with no possibility
// of buffering because this message will be destroyed upon leaving this
// section of code, and with it will go the buffer containing all the
// inputs. Obviously, it must be sent BEFORE that happens.
SendMsg(&msg, true);
}
break;
case NetMsg::INPUT_DATA:
{
// Get id and verify that it's for a dropped client, which is the only
// situation in which we currently use this mechanism.
Net::ID id = pmsg->msg.inputData.id;
ASSERT(m_aPeers[id].m_state == CPeer::Dropped);
// Copy the supplied data to the input buffer for the specified peer. We
// have blind faith in the server, and assume it would never send us anything
// that was bad for us. :)
Net::SEQ seq = pmsg->msg.inputData.seqStart;
for (short s = 0; s < pmsg->msg.inputData.sNum; s++)
{
m_aPeers[id].m_netinput.PutFrameTime(seq, pmsg->msg.inputData.pFrameTimes[s]); // *SPA
m_aPeers[id].m_netinput.Put(seq++, pmsg->msg.inputData.pInputs[s]);
}
}
break;
case NetMsg::INPUT_MARK:
{
// Get id and verify that it's for a dropped client, which is the only
// situation in which we currently use this mechanism.
Net::ID id = pmsg->msg.inputMark.id;
ASSERT(m_aPeers[id].m_state == CPeer::Dropped);
// The specified seq indicates the last seq for which the peer's input buffer
// should be used. This value could be ahead of m_seqFrame if other peer's
// are further ahead than us, or could be equal to m_SeqFrame (which, remember
// is the frame we're trying to do). Or, it could be one LESS than m_seqFrame!
// Consider that if we happen to be the furthest ahead of anyone, then the
// frame we last did would be the frame the entire drop sequence was based
// on, so that would be the last valid frame for the dropped peer. And the
// last frame we did is one LESS than m_seqFrame. So, we verify that the
// specified seq is >= m_seqFrame-1.
ASSERT(SEQ_GTE(pmsg->msg.inputMark.seqMark, (Net::SEQ)(m_seqFrame - (Net::SEQ)1)));
// Set peers last active frame
m_aPeers[id].m_seqLastActive = pmsg->msg.inputMark.seqMark;
// If the specified seq is m_seqFrame-1, then the peer is already inactive
// since we already used that input. Otherwise, it will remain active until
// we use that input.
if (m_aPeers[id].m_seqLastActive == (Net::SEQ)(m_seqFrame - (Net::SEQ)1))
m_aPeers[id].m_bInactive = true;
else
m_aPeers[id].m_bInactive = false;
}
break;
case NetMsg::CHAT:
// Return this message to caller
bGotMsgForCaller = true;
break;
case NetMsg::SETUP_GAME:
// Return this message to caller
bGotMsgForCaller = true;
break;
case NetMsg::START_GAME:
// Get some items of interest out of the message
m_idServer = pmsg->msg.startGame.idServer;
m_lFrameTime = (long)pmsg->msg.startGame.sFrameTime;
m_seqMaxAhead = pmsg->msg.startGame.seqMaxAhead;
m_seqInputNotYetSent = m_seqMaxAhead + 1; // *SPA
// Game started, but we always start out "not playing"
m_bGameStarted = true;
m_bPlaying = false;
// Return this message to caller
bGotMsgForCaller = true;
break;
case NetMsg::ABORT_GAME:
// Return this message to caller
bGotMsgForCaller = true;
m_bPlaying = false;
break;
case NetMsg::START_REALM:
{
// Start playing
m_bPlaying = true;
// *SPA 12/30/97 We can send the first frame now
m_bSendNextFrame = true;
m_u16PackageID = 0;
Net::ID id = 0;
for (id = 0; id < Net::MaxNumIDs; id++)
{
// Only set time for peers that are joined
if (m_aPeers[id].m_state == CPeer::Joined)
m_aPeers[id].m_lLastReceiveTime = rspGetMilliseconds();
}
}
break;
case NetMsg::HALT_REALM:
// Set the halt frame
SetHaltFrame(pmsg->msg.haltRealm.seqHalt);
break;
case NetMsg::NEXT_REALM:
// Set the halt frame. The server will never (in theory) allow more
// than one halt frame to be in effect at any time.
SetHaltFrame(pmsg->msg.nextRealm.seqHalt);
m_bSendNextFrame = false;
// Note that we don't return this message to the caller. Instead,
// we set this flag, which tells us to generate a NEXT_REALM for
// the caller when we reach the halt frame.
m_bNextRealmPending = true;
break;
case NetMsg::PROGRESS_REALM:
// Whenever the server receives a READY_REALM message from a client,
// it sends this message to all clients, telling them how many clients
// are ready. This is just a simple status message intended to allow
// the app to give the user feedback about what is happening.
// Return this message to caller
bGotMsgForCaller = true;
break;
case NetMsg::PROCEED:
// This is a simple app-level message used by the server to tell all
// players to "proceed" to whatever the next step of the program is
// Return this message to caller
bGotMsgForCaller = true;
break;
case NetMsg::PING:
// Calculate ping time and stuff result back into message so high
// level has easy access to it.
// m_lLatestPingTime = rspGetMilliseconds() - pmsg->msg.ping.lTimeStamp;
// pmsg->msg.ping.lLatestPingResult = m_lLatestPingTime;
break;
case NetMsg::RAND:
break;
default:
TRACE("CNetClient::GetMsg(): Unexpected message received!\n");
break;
}
}
}
// If we have a message for the caller, use it. Otherwise, return a NOTHING msg
if (!bGotMsgForCaller)
{
// Create a nothing message
pmsg->msg.nothing.ucType = NetMsg::NOTHING;
}
}
////////////////////////////////////////////////////////////////////////////////